Coder Social home page Coder Social logo

tivix / django-cron Goto Github PK

View Code? Open in Web Editor NEW
885.0 885.0 184.0 267 KB

Write cron business logic as a Python class and let this app do the rest! It enables Django projects to schedule cron tasks, tracks their success / failures, manages contention (via a cache) etc. Basically takes care of all the boring work for you :-)

Home Page: www.tivix.com

License: MIT License

Python 100.00%

django-cron's Introduction

django-cron

image

image

image

Django-cron lets you run Django/Python code on a recurring basis providing basic plumbing to track and execute tasks. The 2 most common ways in which most people go about this is either writing custom python scripts or a management command per cron (leads to too many management commands!). Along with that some mechanism to track success, failure etc. is also usually necesary.

This app solves both issues to a reasonable extent. This is by no means a replacement for queues like Celery ( http://celeryproject.org/ ) etc.

Documentation

http://django-cron.readthedocs.org/en/latest/

This open-source app is brought to you by Tivix, Inc. ( http://tivix.com/ )

Demo App

https://github.com/Tivix/django-crone-demo

django-cron's People

Contributors

dependabot[bot] avatar dfryta avatar dgominik avatar dmedvinsky avatar eriktelepovsky avatar evenicoulddoit avatar ghinch avatar ihoru avatar jedrzejmaluszczak avatar jonathanberger avatar kas avatar maciej-jaworski avatar mateusz-sikora avatar maxim-kht avatar mickeyckm avatar mjaworski avatar mozillazg avatar name-no avatar nerjan avatar palfrey avatar pennersr avatar pjthomas404 avatar raisins avatar santtu avatar sennoy avatar tammyalexandra avatar valeriansaliou avatar weslord avatar wtemmerman avatar xzzy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-cron's Issues

Timezone errors

Hi,

Need to update the code use timezone.now() instead of datetime.now()

Cheers,
Mickey

Incorrect RUN_AT_TIMES with different Time Zone

I have been using RUN_AT_TIMES with version 0.4.0 and with a different timezone, all run in the expected date. My configuration is:
TIME_ZONE = 'America/Lima'
USE_TZ = True

And with the time server in the same timezone as django configuration (UTC-05:00 - Lima)

With the version 0.4.1, my crons run in UTC time and ignore my Time Zone.

ImportError: No module named 'base'

I'm getting a really weird error whenever I try to do 'manage.py runcrons'.

>manage.py runcrons
Traceback (most recent call last):
  File "..\project\django_cron\__init__.py", line 181, in get_lock_class
    return get_class(name)
  File "..\project\django_cron\__init__.py", line 22, in get_class
    m = __import__(module)
  File "..\project\django_cron\backends\lock\cache.py", line 1, in <module>
    from base import DjangoCronJobLock
ImportError: No module named 'base'

I've tried installing through pip, downloading the repo and manually putting it in the project, and changing cache.py line 1 to

from ..base import DjangoCronJobLock

with no luck. I'm using Django 1.7.3 and Python 3.4.1.
Any thoughts?

Make sure these are valid cron class names

When I run "python manage.py runcrons", I get "Make sure these are valid cron class names" error.
My settings.py has this: "
CRON_CLASSES = [
'my_app.cron.MyJob',
]"
And, my files is gose like this:
*my_app
*cron.py

In the cron.py, I also create class MyJob, but I get this "Make sure these are valid cron class names".

Why? Thank you.

In doubt

First of all, thanks for this app/project, it will be really helpful to me.

One thing that is making me confused is the fact that I'm able to define run_every_min or run_at and later at the docs it says that I'll need to setup a cronjob for it.

So, defining those values works only like an if? In case I set it to run_every_min to 60, and set my cronjob to run every 60 minutes as well, what will that parameter do ?

Remove succeeded cron job

Hey all,
Need your advice on best practice :)

I am running cron job every minute to check if there is anything I need users to notify. If so, I send them push notifications. Everything works great, however it logs me 1440 database rows a day, which I think is not great. Is it a way to remove row immediately if cron job has finished with success?

Thank you in advance,
Andrew

Not starting schedule jobs every 2 minutes

Hello All,

I have written code according to documentation.
My setting file is
CRON_CLASSES = [
"cronapp.cron.MyCronJob",
"django_cron.cron.FailedRunsNotificationCronJob"
]
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_cron',
)

My cron.py file is within my app directory
from django_cron import CronJobBase, Schedule
class MyCronJob(CronJobBase):
RUN_EVERY_MINS = 10
schedule = Schedule(run_every_mins=RUN_EVERY_MINS)
code = 'cronapp.MyCronJob' # a unique code

def do(self):
    f = open('/home/user/Desktop/crontest/yogesh.txt','w')
    f.write(str(datetime.now()))
    f.close()

and first time when i am going to run command "python manage.py runcrons" code is executed.
after that this code not executed every 2 min.
I am going to setup cron job first time can you please let me know. what i am doing wrong.
Regards
Yogesh D

Testing if datetime is aware fails

manager.run(force)
  File "/var/www/hosts/bettersubbox.com/dev/local/lib/python2.7/site-packages/django_cron/__init__.py", line 209, in run
    with self.lock_class(cron_job_class, self.silent):
  File "/var/www/hosts/bettersubbox.com/dev/local/lib/python2.7/site-packages/django_cron/backends/lock/base.py", line 60, in __enter__
    raise self.LockFailedException(self.lock_failed_message())
  File "/var/www/hosts/bettersubbox.com/dev/local/lib/python2.7/site-packages/django_cron/backends/lock/cache.py", line 47, in lock_failed_message
    started = self.get_running_lock_date()
  File "/var/www/hosts/bettersubbox.com/dev/local/lib/python2.7/site-packages/django_cron/backends/lock/cache.py", line 90, in get_running_lock_date
    if not timezone.is_aware(date):
  File "/var/www/hosts/bettersubbox.com/dev/local/lib/python2.7/site-packages/django/utils/timezone.py", line 340, in is_aware
    return value.utcoffset() is not None
AttributeError: 'NoneType' object has no attribute 'utcoffset'
``

Django 1.9, failed once out of thousands of runs...

Can't run a job at specified time

I thought that this will allow to run a job at say 11:00 pm as the cron allows to do that.

Any way to actually do it? or this is a Feature request?

Error in file locking backend with python 3

File ".../lib/python3.4/site-packages/django_cron/backends/lock/file.py", line 20, in lock
f = open(lock_name, 'w+', 0)
ValueError: can't have unbuffered text I/O

For python3, should change line 20 to f = open(lock_name, 'wb+', 0) and line 37 to f.write(bytearray(str(os.getpid()), 'utf-8'))

Django 1.9 compatibility

In Django 1.9 you can no longer load any models on app startup.

Traceback (most recent call last):
  File "manage.py", line 12, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 324, in execute
    django.setup()
  File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 90, in create
    module = import_module(entry)
  File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/usr/local/lib/python2.7/dist-packages/django_cron/__init__.py", line 6, in <module>
    from django_cron.models import CronJobLog
  File "/usr/local/lib/python2.7/dist-packages/django_cron/models.py", line 4, in <module>
    class CronJobLog(models.Model):
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 94, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 239, in get_containing_app_config
    self.check_apps_ready()
  File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

Warning on Django 1.8

/usr/local/lib/python2.7/dist-packages/django_cron/models.py:4: RemovedInDjango19Warning: Model class django_cron.models.CronJobLog doesn't declare an explicit app_label and either isn't in an application in INSTALLED_APPS or else was imported before its application was loaded. This will no longer be supported in Django 1.9.
class CronJobLog(models.Model):

Multiple CronJobBase running when ALLOW_PARALLEL_RUNS is set to False

Hi, first of all, thank you for your work. It is very useful app. I use it in many projects, but I came into problem in the last one. I always set ALLOW_PARALLEL_RUNS to False in all of my CronJobBase classes, but runcrons command always run long running tasks multiple times for me and server resources get overloaded in few minutes.

This is my cron job task configuration:

class LongRunningTask(CronJobBase):
    ALLOW_PARALLEL_RUNS = False
    RUN_EVERY_MINS = 30  # every 30 minutes
    RETRY_AFTER_FAILURE_MINS =  30
    MIN_NUM_FAILURES = 1
    schedule = Schedule(
        run_every_mins=RUN_EVERY_MINS, 
        retry_after_failure_mins=RETRY_AFTER_FAILURE_MINS
    )

crontab is set to check cron tasks every minute:
*/1 * * * * python manage.py runcrons;

I also tried to run runcrons for specific task as well, same result:
*/1 * * * * python manage.py runcrons myapp.cron.LongRunningTask;

Is there something wrong with my ALLOW_PARALLEL_RUNS configuration? Or is there some another option to disable multiple task running?

I tried versions 0.3.5 and 0.3.3. Same behaviour.

Thank you very much for your help in advance.

Deprecated

Works perfect when I have only one cron class.
If the second one is added, I get the error:

Running python manage.py runcrons -v 3 on dj-portal... up, run.5829
[WARNING] /app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py:265: RemovedInDjango110Warning: OptionParser usage for Django management commands is deprecated, use ArgumentParser instead
  RemovedInDjango110Warning)
 [base.py](265)

Can't run the task at second time

Hello,I found a problem ,when i run the command python manage.py runcrons ,my task just run one time and wouldn't run anymore.
Here is My code:

mobile/cron.py
class SimpleTaskCronJob(CronJobBase):
    RUN_EVERY_MINS = 1    

    schedule = Schedule(run_every_mins=RUN_EVERY_MINS)
    code = 'mobile.cron.SimpleTaskCronJob'

    def do(self):
        print "runing the task "
        msg = "I have done task in %s sec: %s"
settings.py
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_cron',
    'mobile',
)

CRON_CLASSES = [
    "mobile.cron.SimpleTaskCronJob",
]

is there any problem with my code??

South migration is broken

Hi there, when I run python manage.py migrate I get the error:

django.core.exceptions.ImproperlyConfigured: App with label cron could not be found

django_cron is installed in installed apps as described!

Thanks

optparse.make_option method is deprecated in Django 1.10

Running runcrons:

.../venv/lib/python2.7/site-packages/django/core/management/base.py:265: RemovedInDjango110Warning: OptionParser usage for Django management commands is deprecated, use ArgumentParser instead
RemovedInDjango110Warning)

Looks like all you need to do is replace the "option_list" block at the top of the Command class with:

def add_arguments(self, parser):
    parser.add_argument('--force', action='store_true', help='Force cron runs')
    parser.add_argument('--silent', action='store_true', help='Do not push any message on console')

DateTimeField received a naive datetime while time zone support is active.

The above warning occurs when running manage.py runcrons on Django 1.4. The complete traceback is:

Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
    utility.execute()
  File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 382, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/lib/python2.7/dist-packages/django/core/management/base.py", line 196, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/lib/python2.7/dist-packages/django/core/management/base.py", line 232, in execute
    output = self.handle(*args, **options)
  File "/home/joel/.virtualenvs/ecomarket/local/lib/python2.7/site-packages/django_cron/management/commands/runcrons.py", line 57, in handle
    silent=options['silent'])
  File "/home/joel/.virtualenvs/ecomarket/local/lib/python2.7/site-packages/django_cron/management/commands/runcrons.py", line 74, in run_cron_with_cache_check
    CronJobManager.run(instance, force)
  File "/home/joel/.virtualenvs/ecomarket/local/lib/python2.7/site-packages/django_cron/__init__.py", line 91, in run
    if CronJobManager.__should_run_now(cron_job, force):
  File "/home/joel/.virtualenvs/ecomarket/local/lib/python2.7/site-packages/django_cron/__init__.py", line 78, in __should_run_now
    qset = CronJobLog.objects.filter(code=cron_job.code, start_time__gt=datetime.today().date(), ran_at_time=time_data)
  File "/usr/lib/python2.7/dist-packages/django/db/models/manager.py", line 143, in filter
    return self.get_query_set().filter(*args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/django/db/models/query.py", line 624, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/django/db/models/query.py", line 642, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1250, in add_q
    can_reuse=used_aliases, force_having=force_having)
  File "/usr/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 1185, in add_filter
    connector)
  File "/usr/lib/python2.7/dist-packages/django/db/models/sql/where.py", line 69, in add
    value = obj.prepare(lookup_type, value)
  File "/usr/lib/python2.7/dist-packages/django/db/models/sql/where.py", line 320, in prepare
    return self.field.get_prep_lookup(lookup_type, value)
  File "/usr/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 709, in get_prep_lookup
    return super(DateField, self).get_prep_lookup(lookup_type, value)
  File "/usr/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 310, in get_prep_lookup
    return self.get_prep_value(value)
  File "/usr/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 801, in get_prep_value
    value = self.to_python(value)
  File "/usr/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 761, in to_python
    RuntimeWarning)
RuntimeWarning: DateTimeField received a naive datetime (2013-08-22 00:00:00) while time zone support is active.

This comes from the fact that you are passing a datetime.date object to a DateTimeField, which is unsupported. A workaround is to use a timezone-aware datetime object (eg. by using django.utils.timezone.now) and setting the time to midnight.

Although this is only a warning, it is causing a large amount of email for us as we have runcrons set up to run every five minutes and email us any output from stderr.

django_cron stops working if date will be (temporary, by error, etc) in future.

Consider the case:

  • the server date was set temporary in future (by error, or for testing, …).
  • django cron job executed once
  • then server date returns to normal (sync by ntpdate etc)

Then, accorging to CronJobManager.should_run_now

last_job = CronJobLog.objects.filter(code=cron_job.code).latest('start_time')

if get_current_time() > last_job.start_time + timedelta(minutes=cron_job.schedule.retry_after_failure_mins):

Django_cron stop working until this future is back.

:(

IMHO, when determining last_job, django_cron should filter/ignore jobs with future dates.

Model class django_cron.models.CronJobLog doesn't declare an explicit app_label and either isn't in an application in INSTALLED_APPS

I get the below error when executing python manage.py runcrons

... venv/local/lib/python2.7/site-packages/django_cron/models.py:4: 
RemovedInDjango19Warning: Model class django_cron.models.CronJobLog 
doesn't declare an explicit app_label and either isn't in an application in 
INSTALLED_APPS or else was imported before its application was loaded. This 
will no longer be supported in Django 1.9.

Error 500 on sorting by duration time on admin panel

Hi,

I'm using Django_cron and I want to know what are the longest duration time of my tasks. On the admin panel, I want to sort by duration time and when I do, I got a 500 errors as below :

Environment:

Request Method: GET
Request URL: http://localhost:8000/admin/django_cron/cronjoblog/?o=4.-2

Django Version: 1.8
Python Version: 3.5.1
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.humanize',
 'django.contrib.gis',
 'django_extensions',
 'django_markwhat',
 'django_markdown',
 'jsonify',
 'leaflet',
 'waliki',
 'waliki.git',
 'waliki.attachments',
 'waliki.togetherjs',
 'corsheaders',
 'mail_templated',
 'notifications',
 'import_export',
 'django_cron',
 'stdimage',
 'ttn',
 'wiki',
 'debug_toolbar')
Installed Middleware:
('debug_toolbar.middleware.DebugToolbarMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'corsheaders.middleware.CorsMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware',)


Traceback:
File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python3.5/site-packages/django/contrib/admin/options.py" in wrapper
  616.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/contrib/admin/sites.py" in inner
  233.             return view(request, *args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper
  34.             return bound_func(*args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py" in bound_func
  30.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/local/lib/python3.5/site-packages/django/contrib/admin/options.py" in changelist_view
  1655.             selection_note=_('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
File "/usr/local/lib/python3.5/site-packages/django/db/models/query.py" in __len__
  144.         self._fetch_all()
File "/usr/local/lib/python3.5/site-packages/django/db/models/query.py" in _fetch_all
  965.             self._result_cache = list(self.iterator())
File "/usr/local/lib/python3.5/site-packages/django/db/models/query.py" in iterator
  238.         results = compiler.execute_sql()
File "/usr/local/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in execute_sql
  818.             sql, params = self.as_sql()
File "/usr/local/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in as_sql
  367.             extra_select, order_by, group_by = self.pre_sql_setup()
File "/usr/local/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in pre_sql_setup
  49.         order_by = self.get_order_by()
File "/usr/local/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in get_order_by
  276.                     field, self.query.get_meta(), default_order=asc))
File "/usr/local/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in find_ordering_name
  547.         field, targets, alias, joins, path, opts = self._setup_joins(pieces, opts, alias)
File "/usr/local/lib/python3.5/site-packages/django/db/models/sql/compiler.py" in _setup_joins
  580.             pieces, opts, alias)
File "/usr/local/lib/python3.5/site-packages/django/db/models/sql/query.py" in setup_joins
  1461.             names, opts, allow_many, fail_on_missing=True)
File "/usr/local/lib/python3.5/site-packages/django/db/models/sql/query.py" in names_to_path
  1386.                                      "Choices are: %s" % (name, ", ".join(available)))

Exception Type: FieldError at /admin/django_cron/cronjoblog/
Exception Value: Cannot resolve keyword 'duration' into field. Choices are: code, end_time, id, is_success, message, ran_at_time, start_time

I'm using Django 1.8

Thank you very much

Pull Request: logging to message

Haven't found the possibility to add Pull Request so I add it here

I'd like to log some data during command running and save it the message field.

Question about calling runcrons while a previous job is happening

If manage.py runcrons is called while a django-cron do function hasn't yet finished running, and that django-cron do function isn't scheduled to run again yet at that point in time, will there be a problem? I'm asking because I'm wondering whether some issues I'm experiencing might be due to having scheduled the (crontab -e) cron job to run too frequently.

runcrons is once-and-for-all?

The following cron job class is intended to send email every min once running "runcrons" command. But in fact, it only sends out one email every time I run runcrons command (instead of send one email per minute). That defeats the purpose of cron... Am I missing something?

class TestCron(CronJobBase):
schedule = Schedule(run_every_mins=1)
code = 'test_cron_philip'

def do(self):
    send_mail('cron test', 'body is test body', '[email protected]',
              ['[email protected]'],fail_silently=False)

Not able to configure cron to run every minute

Hi,

I have used django-cron for setting up cron task for my project and I am able to run the scripts manually with command python manage.py runcrons and it is running for only one time. Now I want to run script for every minute and for that I have to use crontab -e and I have done in the same way as told in documentation but with no success.

  • * * * * source /home/ubuntu/.bashrc && /usr/bin/python && source /home/aakash/Project/project-name/src/api/bin/activate && python /home/aakash/Project/project-name/src/manage.py runcrons > /home/aakash/Project/cronjob.log

Can you please help me on that

Scheduling with run_at_times and crontab entry

Great library and we are using it. Im actually a bit confused on this topic. Say I want a job to run at 4:20 pm every day and I have added run_at_times to ['16:20'] .

I know the library works by adding runcrons command to crontab but I'm not aware the best way to add the entry to crontab.

If I add a crontab entry every 5 minutes (*/5 * * * ), would it reach a point where crontab would run it and skip the 4:20pm mark and not run it at all? If I edit crontab with ( * * * *) how am I sure that cron will run it exacrtly at 4:20pm such that django-cron can run too.

Thanks, hope that made sense.

how to run a cron many times

i have successfully run my job with commond :"./manager.py runcrons"

i set it : RUN_EVERY_MINS =1 and ALLOW_PARALLEL_RUNS = True
however, it just ran once ,then it closed. No matter how long time goes by.
so , i have a question : does it just be able to run a job one time successfully ?

The CronJobManager doesn't check is the job is running

  • Set your crontab to run jobs every 1 minute
  • Set a big job to run every 10 minutes

If the big job lasts more than 1 minute, there will be multiple executions of the same job (one every minute until the job is finished).

That's because the log of the cronjob is only saved when the job is finished.

ImportError: No module named 'django-cron'

after pip install django-cron ,i hvae add django-cron to my Django settings INSTALLED_APPS

but there is some trouble when I run python manage.py migrate django_cron

$ python manage.py shellpython manage.py migrate django_cron
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "D:\Python64\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line
    utility.execute()
  File "D:\Python64\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 327, in execute
    django.setup()
  File "D:\Python64\Anaconda3\lib\site-packages\django\__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "D:\Python64\Anaconda3\lib\site-packages\django\apps\registry.py", line 85, in populate
    app_config = AppConfig.create(entry)
  File "D:\Python64\Anaconda3\lib\site-packages\django\apps\config.py", line 90, in create
    module = import_module(entry)
  File "D:\Python64\Anaconda3\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked
ImportError: No module named 'django-cron'

Not working

Hi,
i do everything like readme file.
Right now i can do python manage.py runcrons and it works.

my cron job looks like this:

class MyCronJob(CronJobBase):
RUN_EVERY_MINS = 1 # mins
MIN_NUM_FAILURES = 3

schedule = Schedule(run_every_mins=RUN_EVERY_MINS)
code = 'my_app.my_cron_job'    # a unique code

def do(self):
    print "pass"

So, it prints "pass" when i type "python manage.py runcrons"
But when i run server with "python manage.py runserver", server runs but no string shown in console...
Can you help me? Thanks in advance!

South Dependency is Too Strict

At first I was going to propose changing the South dependency to South>=0.7.2, but now I'm wondering if it actually needs that dependency at all.

At the very least, we should be able to use django-cron with a greater version of South, but I don't think South is even truly required.

Django 1.8 Compatibility

Hi,

The documents says this only supports up until 1.7. Can you update the documents and or fix this package to support Django 1.8?

How to make a fail run?

Hello!

First of all thank you for this piece of software! :)

I see there is an option RETRY_AFTER_FAILURE_MINS, but by reading through the README file I can't understand how do I tell for my class that function do has failed to do its job?

Run cron once a week / a month

Currently it's not possible to run cron on a specified date and hour every month, i.e. issuing invoices 15th of a month. It would be useful, if one could specify "run cron every 15th of a month at 3 am". I could be provided in a similar way to RUN_AT_TIMES, for example RUN_AT_DAYS_OF_MONTH=['15:03:00'], where first part of string is a day of a month, second part is an hour and last part is minutes.

Going further, it would be also useful, if one could specify "run cron every monday at 3 am". In that case RUN_AT_DAYS_OF_WEEK could be used with strings like 'Mon:03:00', where first part is a day of a week, the rest is hour and minutes.

To provide more flexibility, also management command running specified cron class could be added, so it would be possible to specify in crontab to run that cron at that time without use of runcrons management command.

Cronjob is run every time runcrons is called

We just noticed some strange behaviour on our staging server after updating from django-cron 0.4.6 to 0.5.0. One of our jobs looks like this:

class AnalyticsReportJob(CronJobBase):
    RUN_EVERY_MINS = 60 * 24

    schedule = Schedule(run_every_mins=RUN_EVERY_MINS)
    code = 'analytics.report'

    def do(self):
        do_stuff()

It's supposed to report on gathered analytics data once a day, basically just collecting and sending out some emails. Real cron is calling runcrons every minute. After experiencing some heavy load and unexpected behaviour, we could confirm that do_stuff() is actually executed every minute, leading to several critical issues including zombie processes.

Failed Cron task continuously running if task is failed

There is no configuration for stopping task if it fails for a fixed number of times.
Currently if my task is failing it will run again and again until it success.
there should be a config setting for "Max num of failures" to stop that.

there is one 'MIN_NUM_FAILURES' attribute to set for email notification but this does not stops task!

How does this work in a distributed environment?

Hi,

Thanks for this great library! I'm wondering how this will work in a distributed environment with many App/Web servers. If each app server has the cron configured, will there be issues with multiple servers performing the same job or is that prevented using Database Locks (or something like that?).

Any additional info on this would be greatly appreciated.

Thanks,
Lyle

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.