Python:每 x 分钟交替一次函数

标签 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')

如何让 foo 和 bar 函数交替运行,比如每隔 30 分钟运行一次? 含义:第一个 30 分钟 - 运行 foo,第二个 30 分钟 - 运行 bar,第三个 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()

工作正常。

最佳答案

请记住,函数是 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

关于Python:每 x 分钟交替一次函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6100441/

相关文章:

python - 以元组为键将字典转换为数据框

java - 在 Java 中同步人群(第 2 部分)

multithreading - sem_init(…) : What is the value parameter for?

function - 如何从程序集中调用 Rust 函数?

javascript - 你应该使用局部内部函数吗?

python - 在 C++ 中嵌入 Python。传递接收列表列表的字符串 vector

python - 以 root 身份在启动时运行 Python 脚本

python - 如何解决类型错误: RelatedManager object is not iterable

java - 有什么好的Java线程迁移包吗?

c++ - 指针数组分配的段错误?