14👍
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) }, }
6👍
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.
- GeoDjango on Windows: Try setting GDAL_LIBRARY_PATH in your settings
- Add context to every Django Admin page
- Django 1.4 – Redirect to Non-HTTP urls
- Django – Dictionary update sequence element #0 has length 1; 2 is required
- Direct assignment to the reverse side of a related set is prohibited. Use addresses.set() instead
4👍
If you really need to do this and you need a solution quickly, you could resort to adding:
sleep <num_seconds>
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).
- Django Help: AttributeError: 'module' object has no attribute 'Charfield'
- Active Django settings file from Celery worker
- Django Per Object Permission for Your Own User Model
- Psycopg2 disconnects from server
2👍
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
- Database "is being accessed by other users" error when using ThreadPoolExecutor with Django
- Django on Kubernetes Deployment: Best practices for DB Migrations
- Django custom manager with ManyToManyField
- IPython on Windows – No highlighting or Auto-complete