简体   繁体   English

如何连续运行python脚本一天

[英]how to run a python script constantly for a day

I have a python script that search for something in the internet.the script takes 2 minutes to finish.我有一个在 Internet 上搜索内容的 python 脚本。脚本需要 2 分钟才能完成。 after 2 minutes script will exit and the job is done. 2 分钟后脚本将退出并完成工作。

but i want to run this script on my computer constantly for a day without stopping.但我想在我的电脑上不停地运行这个脚本一天。 it means i want to rerun the script after it's finished for a day.这意味着我想在完成一天后重新运行脚本。

i tried something like this so far:到目前为止,我尝试过这样的事情:

status = True
def setstatus(stat):
    global status
    if staus:
       status = not stat
timer = Timer(1440,setstatus,[True])
timer.start()

while status:
   # do the job

any suggestion?有什么建议吗?

time.time() will give you the current time (in seconds from some time origin, in fact at the start of 1970). time.time()将为您提供当前时间(从某个时间原点开始的秒数,实际上是在 1970 年初)。 Calculate the end time by adding a number of seconds from the current time, and loop until then.通过从当前时间添加秒数来计算结束时间,然后循环直到那时。

import time

end_time = time.time() + 86400

while time.time() < end_time:
    # do the job

Obviously this will keep using as much CPU as your job requires -- your stated aim is "to run this script on my computer constantly for a day without stopping" and this will do what you have asked for.显然,这将继续使用与您的工作所需的 CPU 一样多的 CPU——您声明的目标是“在我的计算机上不断运行此脚本一天而不停止” ,这将满足您的要求。 If in fact you want it to reduce CPU consumption by sleeping for a while on each iteration, then you can insert a time.sleep(...) in the loop (with sleep time value in seconds).如果实际上您希望它通过在每次迭代中休眠一段时间来减少 CPU 消耗,那么您可以在循环中插入一个time.sleep(...) (休眠时间值以秒为单位)。

Only works for GNU/Unix based systems.仅适用于基于 GNU/Unix 的系统。

You can use Cron .您可以使用Cron

For exemple, running a script everyday at 10 am例如,每天上午 10 点运行一个脚本

Enter crontab -e in terminal.在终端输入crontab -e Add 0 10 * * * /path/to/script.py to the prompted file.0 10 * * * /path/to/script.py添加到提示文件中。

If you are using it with a web-scraper as your question states, you can have a shell script to encapsulate your python script.如果您按照问题所述将它与网络爬虫一起使用,则可以使用 shell 脚本来封装您的 python 脚本。

#!/bin/bash

# setup variables
DATE=$(date +"%Y-%m-%d-%H-%M")
SCRIPT_FILE="path/to/python/script.py"
OUTPUT_FILE="path/to/save/outputs/${DATE}.json"

# activate virtualenv and run scrapy, for example
source path/to/venv/bin/activate
scrapy runspider ${SCRIPT_FILE} -o ${OUTPUT_FILE}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM