【问题标题】:Python Run Two Functions With Different Timers In One DaemonPython 在一个守护进程中运行两个具有不同计时器的函数
【发布时间】:2012-05-28 11:29:33
【问题描述】:

我在两个不同的脚本中使用template python daemon discussed here 来启动两个单独的守护进程。我想将它们组合成一个具有一个锁定文件等的守护程序脚本。但是,每个都有不同的循环计时器,一个在 1 分钟,另一个在 5 分钟。我从这个开始:

import os
import subprocess
import time
from daemon import runner

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/test.pid'
        self.pidfile_timeout = 5
    def run(self):

        try:
            while True:

                print "hello!"

                # set the sleep time for repeated action here:
                time.sleep(1)

        except Exception, e:
            raise


app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

显而易见的事情是创建另一个类,但我希望 pidfile 等基本内容保持不变。

【问题讨论】:

  • 将常量保留在App 类中,并为每个应用创建一个子类

标签: python linux timer daemon runner


【解决方案1】:

我不完全明白你为什么要这样做,但这应该可行:

让run_A 和run_B 函数做两个独立的事情(显然不是那些名字),包括睡眠等等。这并不重要,但将这些放在 App 类之外可能是有意义的。

然后创建一个如下所示的run 函数:

def run(self):
    threads = [
         threading.Thread(target=run_A),
         threading.Thread(target=run_B)
    ]

    for thread in threads:
         thread.start()
    for thread in threads:
         thread.join()

这将为每个作业生成一个单独的线程,然后可以继续其愉快的方式。如果您在作业之间有任何共享资源,您将不得不担心锁定。

这假设作业可以快速执行并且确切的时间并不重要;由于 CPython 的GIL,一次只有一个线程会运行 Python 语句,所以如果它们同时弹出,它们的运行速度会慢一些。如果您希望它们能够并行运行,您可以轻松地将其切换为使用 multiprocessing。

这将导致一些“计时器漂移”,因为您使用的是sleep(如果您的守护程序独立运行,也会如此)。如果这很重要,您可以改用中断,或者计算直到下一个五分钟倍数的时间,而不是仅仅休眠五分钟。

【讨论】:

    【解决方案2】:

    如果您的较长延迟不需要准确按时执行,您可以使用一个简单的累加器来跟踪较短操作的几个周期使用了多少时间。如果 LONG_DELAY 是 SHORT_DELAY 的整数倍,下面的代码将完美运行。如果它不是一个精确的倍数,则较长的周期仍将按平均请求的周期执行,但延迟可能会更短或更长,在任何给定的传递中最多为 SHORT_DELAY:

    SHORT_DELAY = 60 # 1 minute
    LONG_DELAY = 300 # 5 minutes
    
    accum = LONG_DELAY
    
    while True:
        do_short_delay_action()
    
        if accum >= LONG_DELAY:
            do_long_delay_action()
            accum -= LONG_DELAY
    
        time.sleep(SHORT_DELAY)
        accum += SHORT_DELAY
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-03
      • 1970-01-01
      • 2012-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      相关资源
      最近更新 更多