我很好奇你如何在后台运行python脚本,每60秒重复一次任务。我知道你可以使用&在后台放置东西,这对这种情况是否有效?高效的Python守护进程
我正在考虑做一个循环,让它等待60秒,然后重新加载,但有些事情感觉不到。
我很好奇你如何在后台运行python脚本,每60秒重复一次任务。我知道你可以使用&在后台放置东西,这对这种情况是否有效?高效的Python守护进程
我正在考虑做一个循环,让它等待60秒,然后重新加载,但有些事情感觉不到。
我认为你的想法几乎正是你想要的。例如:
import time
def do_something():
with open("/tmp/current_time.txt", "w") as f:
f.write("The time is now " + time.ctime())
def run():
while True:
time.sleep(60)
do_something()
if __name__ == "__main__":
run()
致电time.sleep(60)
将使您的程序休眠60秒。如果时间到了,操作系统会唤醒您的程序并运行do_something()
函数,然后重新进入睡眠状态。当你的程序正在睡觉时,它没有任何效率。这是编写后台服务的一般模式。
要真正在命令行中运行这个,你可以使用&:
$ python background_test.py &
在这样做时,从脚本的输出会去同一个终端作为从启动它的一个。您可以将输出重定向到避免这种情况:
$ python background_test.py >stdout.txt 2>stderr.txt &
谢谢你,这正是我正在寻找的。我知道的编程技巧来自JavaScript,并试图在计时器上做任何事情都变成了噩梦! – 2011-01-09 03:36:26
你可能也想看看nohup(例如`nohup python background_test.py`),假设你想让这个守护进程在你注销后继续运行) – Foon 2011-06-13 17:52:21
使用的外壳&可能是因为格雷格所描述的死者最简单的方法。
如果你真的想创建一个强大的守护进程,你需要看看os.fork()命令。
的例子来自Wikipedia:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, time
def createDaemon():
"""
This function create a service/Daemon that will execute a det. task
"""
try:
# Store the Fork PID
pid = os.fork()
if pid > 0:
print 'PID: %d' % pid
os._exit(0)
except OSError, error:
print 'Unable to fork. Error: %d (%s)' % (error.errno, error.strerror)
os._exit(1)
doTask()
def doTask():
"""
This function create a task that will be a daemon
"""
# Open the file in write mode
file = open('/tmp/tarefa.log', 'w')
# Start the write
while True:
print >> file, time.ctime()
file.flush()
time.sleep(2)
# Close the file
file.close()
if __name__ == '__main__':
# Create the Daemon
createDaemon()
然后你可以把你所需要的doTask()
块内的任何任务。
你不需要使用&来启动它,它可以让你自定义执行一点。
不是编写自己的守护进程,而是使用python-daemon来代替! python-daemon实现了性能良好的守护进程规范PEP 3143,“标准守护进程进程库”。
我已经包含了基于这个问题的接受答案的示例代码,即使代码看起来几乎相同,它也有一个重要的根本区别。如果没有python-daemon,则必须使用&
将您的进程置于后台并0123',并在退出shell时阻止进程被杀死。相反,当您运行该程序时,它会自动从您的终端上分离。
例如:
import daemon
import time
def do_something():
while True:
with open("/tmp/current_time.txt", "w") as f:
f.write("The time is now " + time.ctime())
time.sleep(5)
def run():
with daemon.DaemonContext():
do_something()
if __name__ == "__main__":
run()
要实际运行它:
python background_test.py
这里注意没有&
。
另外,this other stackoverflow answer详细解释了使用python-daemon的许多好处。
这取决于你想要的。如果你想安排一个任务重复一次,请看看cron。 – Falmarri 2011-01-09 03:12:29