一、爬虫定时任务python脚本:
对于爬虫任务,通常需要设置定时任务自动启动,每天按时执行爬虫程序,而我们要做的就是通过数据库以及日志查看运行情况是否有异常。下面给出一个简单方便的定时器代码:
# coding:utf-8
'''
2018.03.14
'''
import sys
import time
import datetime
import subprocess
import signal
import os
# 定时函数
def alarm(h, m, s):
target_str = '{h:02d}:{m:02d}:{s:02d}'.format(h=h, m=m, s=s)
print('Set alarm to {0}'.format(target_str))
while True:
time.sleep(1)
now = datetime.datetime.now()
if now.hour < h or now.minute < m or now.second < s:
continue
print('Now is {0} ding ~ ding ~ ding ~'.format(target_str))
return True
try:
h = int(datetime.datetime.now().strftime('%H'))
# 每日按 schedule 运行 run.py
while True:
# schedule -> 9点启动(使用morning账号), 15点10分重启(更换为afternoon账号), 21点停止
# 定时9点开始任务
alarm(9, 0, 0)
print('run `python3.6 run.py %s`')
cmd = 'nohup python3.6 run.py %s 1>msg 2>err &'
os.popen(cmd, 'r', 1024 * 1024)
# 定时21点结束任务
alarm(21, 0, 0)
cmd = 'killall -u "用户名" python %s' # 此处我的关闭是暴力关闭当前账号的所有python进程,你可以根据自己的灵活修改
os.popen(cmd, 'r', 1024)
cmd = 'rm cookies/*'
os.popen(cmd, 'r', 1024)
time.sleep(20000)
h = 0
except KeyboardInterrupt:
sys.exit('schedule: Ctrl-C')
二、爬虫定时任务系统脚本:
经过使用测试,鉴于前面脚本的稳定性不够好,故改用次脚本。
使用此命令进入:
yangwei@iZ2zea1ofhnvumraui4eilZ:~$ crontab -e
进入后界面为空文本:(编辑后为下代码所示)
30 18 * * 1-5 cd /home/yangwei/data-system_new;/usr/bin/nohup /usr/local/bin/python3.6 run.py &
50 10 * * 6,0 cd /home/yangwei/data-system_new;/usr/bin/nohup /usr/local/bin/python3.6 run.py &
59 23 * * * cd /home/yangwei/data-system_new;/bin/sh kill_all.sh &
应用程序启入口为:run.py 路径为:/home/yangwei/data-system_new/run.py
结束进程脚本为:kill_all.sh 路径为:/home/yangwei/data-system_new/kill_all.sh
解释器路径为:/usr/bin/nohup /usr/local/bin/python3.6 (务必确保解释器路径的正确性)
下面解读一下语句的含义:
30 18 * * 1-5 cd /home/yangwei/data-system_new;/usr/bin/nohup /usr/local/bin/python3.6 run.py &
分 时 日 月 周 |《==============命令行=======================》|
注意: * 代表任何时刻都接受的意思。上列举的代码意思是在周一至周五的18:30分执行后面的代码启动程序。
需要了解更多的crontab使用,请使用crontab --help 产看文档根据自己需要进行配置。