Python:每隔x分钟交替执行一次功能

siv*_*iva 10 python multithreading function timer alternate

假如我有以下四个功能:

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')
Run Code Online (Sandbox Code Playgroud)

如何将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()
Run Code Online (Sandbox Code Playgroud)

编辑:我的解决方案与尼古拉斯奈特的投入......

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()
Run Code Online (Sandbox Code Playgroud)

工作良好.

San*_*nta 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
Run Code Online (Sandbox Code Playgroud)


Nic*_*ght 6

你这太复杂了.

while True:
    foo()
    time.sleep(1800)
    foo_kill()
    bar()
    time.sleep(1800)
    bar_kill()
Run Code Online (Sandbox Code Playgroud)

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

functions = [(foo, foo_kill), (bar, bar_kill), ] # Just append more as needed
while True:
    for f, kf in functions:
        f()
        time.sleep(1800)
        kf()
Run Code Online (Sandbox Code Playgroud)