使用Python-crontab和Django-crontab在Django中实现高效定时任务管理

图片[1]-使用Python-crontab和Django-crontab在Django中实现高效定时任务管理-山海云端论坛

Python-crontab实现定时任务:

# coding=utf-8 from crontab import CronTab class CrontabUpdater: def __init__(self): # 创建当前用户的crontab,也可创建其他用户的,需有足够权限 self.cron = CronTab(user=True) def add_crontab_job(self, command_line, time_str, comment_name, user): # 创建任务 job = self.cron.new(command=command_line) # 设置任务执行周期 job.setall(time_str) # 给任务添加标识(comment),方便查询 job.set_comment(comment_name) # 将crontab写入配置文件 self.cron.write_to_user(user=user) def del_crontab_jobs(self, comment_name, user): # 按comment清除多个定时任务,一次write即可 self.cron.remove_all(comment=comment_name) self.cron.remove_all(comment=comment_name + ' =') # 写入配置文件 self.cron.write_to_user(user=user) if __name__ == "__main__": print('start --------') command_line = "/usr/bin/python /mnt/print_time.py" time_str = "* * * * *" comment_name = "Test_Crontab_Job" user = "xue" # 创建一个实例 crontab_updater = CrontabUpdater() # 删除指定任务 print('&&&&&& del_crontab_jobs ') crontab_updater.del_crontab_jobs(comment_name, user) print('end -------')

定时任务执行的Python脚本(print_time.py):

# coding=utf-8 import datetime with open('/mnt/datetime_log.txt', 'a') as f: f.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "\n")

Django-crontab实现定时任务:

安装:

pip install django-crontab

在settings.py文件中添加:

INSTALLED_APPS = ( ... 'django_crontab', ) CRONJOBS = [ ('*/1 * * * *', 'your_app_name.file_name.function_name'), ('*/1 * * * *', 'your_app_name.file_name.function_name', '>> output_file_path_and_name'), ('*/1 * * * *', 'django.core.management.call_command', ['your_command']), ]

操作命令:

# 查看系统中已有的定时任务 python manage.py crontab show # 添加和修改定时任务 python manage.py crontab add # 删除定时任务 python manage.py crontab remove

解决中文字符问题:

在配置文件中添加:

CRONTAB_COMMAND_PREFIX = 'LANG=zh_cn.UTF-8'

开启定时任务:

添加定时任务到系统中。

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容