crontab在python3.6可装可不装,如果运行报错没有模块名则装,装了之后运行报错TypeError: init() got an unexpected keyword argument ‘user’,则卸载pip3 uninstall crontab安装包,安装pip3 install python-crontab
import random
import time
import datetime
from crontab import CronTab
def strTimeProp(start, end, prop, frmt):
stime = time.mktime(time.strptime(start, frmt))
etime = time.mktime(time.strptime(end, frmt))
ptime = stime + prop * (etime - stime)
return int(ptime)
def randomDate(start, end, frmt='%Y-%m-%d %H:%M'):
return time.strftime(frmt, time.localtime(strTimeProp(start, end, random.random(), frmt)))
startDate = datetime.date.today()
afterDate = startDate + datetime.timedelta(days=1)
hou = datetime.datetime.strftime(afterDate, '%Y-%m-%d')
start = time.strftime('%Y-%m-%d %H:%M',time.localtime(time.time()))
end = hou + ' 00:00'
random_date = randomDate(start,end)
aa = datetime.datetime.strptime(random_date,"%Y-%m-%d %H:%M")
print(start,'\n',end)
print(random_date)
secondtime = (aa+datetime.timedelta(minutes=8)).strftime("%Y-%m-%d %H:%M")
print(secondtime)
thirdtime = (aa+datetime.timedelta(minutes=18)).strftime("%Y-%m-%d %H:%M")
print(thirdtime)
def datechuli(dateTime):
minute = dateTime.split(' ')[1].split(':')[1]
hour = dateTime.split(' ')[1].split(':')[0]
mouth = dateTime.split(' ')[0].split('-')[1]
day = dateTime.split(' ')[0].split('-')[2]
return minute+' '+hour+' '+day+' '+mouth + ' *'
my_user_cron = CronTab(user=True)
first = my_user_cron.new(command='cd /home/ubuntu/ft_scrapy/ftimes/ && scrapy crawl ftlist > /home/ubuntu/ft_scrapy/ftimes/ftout.log 2>&1 &', comment='dateinfo')
second = my_user_cron.new(command='cd /home/ubuntu/ft_scrapy/ftimes/ && scrapy crawl ftspiderfetch > /home/ubuntu/ft_scrapy/ftimes/ftart.log 2>&1 &', comment='dateinfo')
third = my_user_cron.new(command='python3 /home/ubuntu/ftimes/ftime.py > /home/ubuntu/ftimes/art.log 2>&1 &', comment='dateinfo')
first.setall(datechuli(random_date))
second.setall(datechuli(secondtime))
third.setall(datechuli(thirdtime))
my_user_cron.write()
参考官方文档
添加链接描述