说,如果我有如下四个功能:的Python:交流功能每隔x分钟
def foo():
subprocess.Popen('start /B someprogramA.exe', shell=True)
def bar():
subprocess.Popen('start /B someprogramB.exe', shell=True)
def foo_kill():
subprocess.Popen('taskkill /IM someprogramA.exe')
def bar_kill():
subprocess.Popen('taskkill /IM someprogramB.exe')
我怎么能替代foo和bar功能,每运行,比如30分钟? 含义:第一个30分钟 - 运行foo
,第二个30分钟 - 运行bar
,第三个30分钟 - 运行foo
,依此类推。每次新的运行应该'杀死'前面的线程/ func。
我有一个倒计时器线程,但不知道如何'交替'的功能。
class Timer(threading.Thread):
def __init__(self, minutes):
self.runTime = minutes
threading.Thread.__init__(self)
class CountDownTimer(Timer):
def run(self):
counter = self.runTime
for sec in range(self.runTime):
#do something
time.sleep(60) #editted from 1800 to 60 - sleeps for a minute
counter -= 1
timeout=30
c=CountDownTimer(timeout)
c.start()
编辑:我和尼古拉斯骑士的输入解决方案...
import threading
import subprocess
import time
timeout=2 #alternate delay gap in minutes
def foo():
subprocess.Popen('start /B notepad.exe', shell=True)
def bar():
subprocess.Popen('start /B calc.exe', shell=True)
def foo_kill():
subprocess.Popen('taskkill /IM notepad.exe')
def bar_kill():
subprocess.Popen('taskkill /IM calc.exe')
class Alternator(threading.Thread):
def __init__(self, timeout):
self.delay_mins = timeout
self.functions = [(foo, foo_kill), (bar, bar_kill)]
threading.Thread.__init__(self)
def run(self):
while True:
for f, kf in self.functions:
f()
time.sleep(self.delay_mins*60)
kf()
a=Alternator(timeout)
a.start()
工作正常。
在线程外运行会限制其他代码执行? – siva 2011-05-24 03:06:36
@siva:为了清楚起见,我不打算“不要在一个单独的线程中运行它”,我的意思是说你太过复杂了。将它包装在一个函数中,然后像你所做的那样在一个线程中启动它就好了。 – 2011-05-24 19:52:50