10

假设我有以下四个功能:

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 分钟?含义:第 1 次 30 分钟 - 跑步foo,第 2 次 30 分钟 - 跑步bar,第 3 次 30 分钟 - 跑步foo,依此类推。每次新的运行都应该“杀死”前一个线程/函数。

我有一个倒数计时器线程,但不确定如何“交替”这些功能。

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()

编辑:我对 Nicholas Knight 输入的解决方案......

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()

工作正常。

4

4 回答 4

10

请记住,函数是 Python 中的一等对象。这意味着您可以将它们存储在变量和容器中!一种方法是:

funcs = [(foo, foo_kill), (bar, bar_kill)]

def run(self):
    counter = self.runTime
    for sec in range(self.runTime):
        runner, killer = funcs[counter % 2]    # the index alternates between 0 and 1
        runner()    # do something
        time.sleep(1800)
        killer()    # kill something
        counter -= 1
于 2011-05-23T17:11:15.580 回答
6

你把这件事复杂化了。

while True:
    foo()
    time.sleep(1800)
    foo_kill()
    bar()
    time.sleep(1800)
    bar_kill()

或者,如果您想稍后轻松添加更多功能:

functions = [(foo, foo_kill), (bar, bar_kill), ] # Just append more as needed
while True:
    for f, kf in functions:
        f()
        time.sleep(1800)
        kf()
于 2011-05-23T17:16:25.827 回答
2

使用变量记录您上次运行的函数。当计时器触发时,运行另一个函数并更新变量。

于 2011-05-23T17:06:19.387 回答
1
import itertools, time

# make sure the function are in the order you want to run them in
# and grouped by the ones that you want to run together
funcs = ((bar_kill, foo), (foo_kill, foo)) 

for func_killer, func in itertools.cycle(funcs)
    func_killer()
    func()
    time.sleep(30 * 60) # pause for 30 minutes

函数可以存储在 python 的列表中,您可以使用循环对其进行迭代for

itertools是一个操作可迭代的模块,例如列表。在这里,我们使用cycle了一个无限循环,它将一遍又一遍地处理列表中的函数funcs

于 2011-05-23T18:17:36.067 回答