python-crontab 设置定时任务

通过python-crontab 设置定时任务(创建设置定时任务的.py文件,并运行即可)
安装包: pip install python-crontab

创建新的py文件, 内容如下:

from crontab import CronTab
# 创建linux系统当前用户的crontab,当然也可以创建其他用户的,但得有足够权限,如:user='root'
cron_manager = CronTab(user=True)


# 创建任务 指明运行python脚本的命令(crontab的默认执行路径为:当前用户的根路径, 因此需要指定绝对路径)
job = cron_manager.new(command='python /root/hong/crontab_test/data_test.py >> /root/hong/crontab_test/data_result.log 2>&1 &')

# 设置任务执行周期,每两分钟执行一次

job.setall('*/2 * * * *')

# 将crontab写入linux系统配置文件
my_user_cron.write()

运行py文件,完成! 此时定时任务已经创建(可在linux终端 输入 contrab -l 查看), crontab 会按照设定的时间 定时调用指定路径下的data_test.py文件。

作者:酷酷的图图
链接:https://www.jianshu.com/p/925de5998e1d