我用python编写了一个爬虫,它可以访问60多个网站,解析HTML,并将数据保存到数据库。
现在,我正在使用cron作业,每15分钟运行一次爬虫。问题是,我无法知道爬虫要花多少时间才能完成(有时可能需要超过15分钟),如果已经在运行,我不想再运行另一个爬虫。
我一直在想,我是否最好使用一个无限循环,并使爬虫成为一个永久运行的进程(但是如何确保爬虫不会失败并退出呢?以及如何在每次退出时重新启动?)。
哪一个更有效率?无限循环还是cron作业?
发布于 2022-04-04 01:04:02
可以在bash脚本中执行无限循环,如下所示:
#!/bin/bash
while ((1)) ; do
python3 -u /path/to/file.py > /path/to/logs.txt
sleep 2
done它将执行脚本,一旦脚本结束(错误与否),它将再次执行。
发布于 2022-04-04 03:56:15
我们可以在cron作业python脚本中添加控件,以跟踪数据库中的运行状态(例如,爬行、启动时间和结束时间)。使用这样的控制结构可能更容易维护:
# query select crawlStartTime and crawlEndTime from DB
# ...
if(crawlEndTime >= crawlStartTime): # the previous crawl job is finished
# update DB set crawlStartTime = now
# do crawling tasks ...
# crawl finished, update DB set crawlEndTime = now
else: # the previous crawl job is not finished
# do not crawl
# in case the job elapsed for far too long
if(now - crawlStartTime >= threshold):
# send alert, kill process, or reset the time recordshttps://stackoverflow.com/questions/67540584
复制相似问题