1. Install Support Package:django-crontab
Installation:pip install django-crontab
2. Sign timing applications
add applications in settings.INSTALLED_APPS in:
INSTALLED_APPS = [
'django_crontab', # 定时任务
]
3. The timer task time format crontab
The basic format regular time:
5 '*' symbol: * * * * * command
sequence corresponding to: time-moon and Week
M: min (0-59). Expressed per min * or * /. 1
H: hour (0-23). (0 indicates 0:00)
D: days (1-31).
m: month (1-12).
d: days of the week (Sunday to 0 ~ 6,0).
Example:
- MyCommand performed once every 1 minute
* /1* * * * myCommand
- Performing the third hour and 15 minutes
3,15 * * * * myCommand
- 3 and performed in the first 15 minutes of 8:00 to 11:00
3,15 8-11 * * * myCommand
- 3 and 15 minutes every day 8:00 to 11:00 is performed
3,15 8-11 */2 * * myCommand
- Every Monday morning, the 3rd and the 15th minute 8:00 to 11:00 of execution
3,15 8-11 * * 1 myCommand
4. Set the timing task
is added in CRONJOBS settings, set the timer task.
- The following is an example of the timing tasks: apps --contents application methods within the next --generate_static_index_html;
- Regular time: run once every minute;
- ">>" symbol: Stitching a scheduled task to run the path to save the results.
CRONJOBS = [
# 每1分钟生成一次首页静态文件
('*/1 * * * *', 'contents.crons.generate_static_index_html', '>> ' + os.path.join(os.path.dirname(BASE_DIR), 'logs/crontab.log'))
]
5. Set Chinese support
in timed tasks, if non-English characters appear, there will be character exception error
- In settings added:
CRONTAB_COMMAND_PREFIX = 'LANG_ALL=zh_cn.UTF-8'
6. Timing management tasks
- Add a scheduled task to the system, start the scheduled task you must perform to change the statement.
$ python manage.py crontab add
- Display timing task activated
$ python manage.py crontab show
- Remove regular task
$ python manage.py crontab remove