每 10 秒运行一次 Python 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34589347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run Python script every 10 seconds
提问by jianbing Ma
I have a function to do some work. The code should repeat 130 million times.
我有一个功能可以做一些工作。代码应该重复 1.3 亿次。
Currently, I use Crontab to run a python script every 1 min. It takes too long a time, I want that this python script run when I run it the first time and keep repeating continuously until the work gets over. I want a 10 seconds break between 2 task. How can I do that?
目前,我使用 Crontab 每 1 分钟运行一次 python 脚本。花费的时间太长,我希望这个python脚本在我第一次运行时运行,并不断重复,直到工作结束。我想在 2 个任务之间休息 10 秒。我怎样才能做到这一点?
采纳答案by Njuguna Mureithi
Try the schedulemodule
试试日程模块
import schedule
import time
def job():
print("I'm working...")
schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
while 1:
schedule.run_pending()
time.sleep(1)
Just run : pip install schedule
赶紧跑 : pip install schedule
回答by jianbing Ma
I think you should use this method:
我认为你应该使用这种方法:
import time
while True:
# code goes here
time.sleep(10)
Actually it's not correct to use while True
since it causes an infinite loop. There should be a condition over there. But since you have not supplied enough data, I cannot actually do that.
实际上使用它是不正确的,while True
因为它会导致无限循环。那边应该有条件。但是由于您没有提供足够的数据,我实际上无法做到这一点。
回答by miguels
One approach might be using threads, you run a thread every N seconds. Since the processing is assumed to be light that might be the solution.
一种方法可能是使用线程,每 N 秒运行一个线程。由于假设处理很轻,因此可能是解决方案。
t=threading.timer(10,function,[function_arguments]) #executes your_function every 10 seconds (example only)
while True:
t.start()
Be aware that the drawback of this solution is that if function() takes more time to process than the seconds_parameter you'll probably concurrency problems.
请注意,此解决方案的缺点是,如果 function() 比 seconds_parameter 花费更多的时间来处理,您可能会出现并发问题。
回答by James Kent
how does the python thread get its work?
for instance if the stuff to work on is defined in some kind of list i would suggest the following approach:
python 线程是如何工作的?
例如,如果要处理的内容在某种列表中定义,我建议采用以下方法:
import time
work = ["list", "of", "jobs", "here"]
for job in work:
# do something with the job
time.sleep(10)
this way the loop will exit as soon as there is no more work to do.
这样,一旦没有更多工作要做,循环就会退出。
回答by salmanwahed
You can look into Supervisor. It's not very complicated to use. You have to schedule your process.
你可以看看Supervisor。使用起来不是很复杂。你必须安排你的过程。
You can add required sleep time in the in your script.
您可以在脚本中添加所需的睡眠时间。
import time
def job()
# tasks of the script
if __name__ == '__main__':
while True:
job()
time.sleep(10)
The job()
function will run in every 10 seconds.
该job()
函数将每 10 秒运行一次。