Django celery crontab every 30 seconds - is it even possible?

℡╲_俬逩灬. 提交于 2019-12-07 04:39:43

问题


Is it possible to run the django celery crontab very 30 seconds DURING SPECIFIC HOURS?

There are only settings for minutes, hours and days.

I have the crontab working, but I'd like to run it every 30 seconds, as opposed to every minute.

Alternatively...

Is it possible to turn the interval on for 30 seconds, and turn on the interval schedule only for a certain period of the day?


回答1:


Very first example they have in the documentation is...

Example: Run the tasks.add task every 30 seconds.

from datetime import timedelta

CELERYBEAT_SCHEDULE = {
    "runs-every-30-seconds": {
        "task": "tasks.add",
        "schedule": timedelta(seconds=30),
        "args": (16, 16)
    },
}



回答2:


If you really need to do this and you need a solution quickly, you could resort to adding: sleep into your script. (obviously you'd need to add a parameter to your script to setup the sleep time to either 0 or 30 seconds and add the script twice to crontab, once with 0 as the parameter, secondly with 30).

Please don't down vote me on this! It's a solution, albeit I'm making it very clear this is not an ideal solution.




回答3:


You could just use

from datetime import timedelta

@periodic_task(run_every=timedelta(seconds=30))
def thirty_second_task():
   now = datetime.now()
   if now.hour == 12 or now.hour == 9:
       your code goes here`

That will run the function every thirty seconds, but it will only run your code if the hour value of the current time is 12 or 9.




回答4:


I would go with your alternative solution by scheduling another task to enable/disable the primary task:

# tasks.py
from djcelery.models import PeriodicTask

@app.task
def toggle_thirty_second_task:
    # you would use whatever you named your task below
    thirty_second_tasks = PeriodicTask.objects.filter(name='runs-every-30-seconds')
    if thirty_second_tasks:
        # this returned an array, so we'll want to look at the first object
        thirty_second_task = thirty_second_tasks[0]
        # toggle the enabled value
        thirty_second_task.enabled = not thirty_second_task.enabled
        thirty_second_task.save()

Then just schedule this task using a crontab for the hours that you need to toggle. Alternatively, you could have a task scheduled to turn it on and one to turn it off and not deal with the toggling logic.

Hope this helps.

sc



来源:https://stackoverflow.com/questions/10596826/django-celery-crontab-every-30-seconds-is-it-even-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!