【问题标题】:Should I use an infinite loop or a cron job for a python crawler?我应该为 python 爬虫使用无限循环还是 cron 作业?
【发布时间】:2022-04-04 12:47:00
【问题描述】:

我用 python 编写了一个爬虫,它可以访问 60 多个网站,解析 HTML,并将数据保存到数据库。

现在我使用 cron 作业每 15 分钟运行一次爬虫。问题是我无法确定爬虫需要多长时间才能完成(有时可能需要超过 15 分钟),如果一个已经在运行,我不想再运行另一个爬虫。

我一直想知道是否最好使用无限循环并使爬虫成为始终运行的永久进程(但我如何确保爬虫不会失败并退出?以及如何每次都重新启动它退出?)。

哪个效率更高?无限循环还是 cron 作业?

【问题讨论】:

    标签: python cron web-crawler


    【解决方案1】:

    您可以在 bash 脚本中执行无限循环,例如:

    #!/bin/bash
    while ((1)) ; do
        python3 -u /path/to/file.py > /path/to/logs.txt
        sleep 2
    done
    

    它会执行脚本,一旦脚本结束(错误与否),它会再次执行

    https://unix.stackexchange.com/questions/521497/how-should-i-run-a-cron-command-which-has-forever-loop

    【讨论】:

      【解决方案2】:

      我们可以在 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 records
      

      【讨论】:

        猜你喜欢
        • 2012-10-20
        • 2013-06-18
        • 2020-03-09
        • 2015-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-15
        • 1970-01-01
        相关资源
        最近更新 更多