gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:20:45 25 4
gpt4 key购买 nike

假设我有如下四个函数:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com