English 中文(简体)
Python 运行两个函数, 使用不同的计时器在一个守护器中运行两个函数
原标题:Python Run Two Functions With Different Timers In One Daemon

我使用< a href=> https://stackoverflow.com/ questions/473620/how-do-you-deposition- a-daemon- in-python>>>template python 守护程序在这里讨论过的两种不同的脚本 来启动两个独立的守护程序。 我想把它们合并成一个包含一个锁定文件等的守护程序脚本。 但是,每个脚本都有不同的循环计时器, 一个在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这种基本的东西 保持恒定不变

最佳回答

我完全不明白你为什么要这么做 但这样应该行得通

使 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 s < a href="http://en.wikipedia.org/wiki/Global_interpreter_Lock" rel=“nofollow”>GIL ,如果它们同时弹出,它们会慢一点,只有一条线将运行 Python 语句,因此,如果它们同时弹出,它们会慢一点。 如果您想要它们能够平行运行, 您可以将它切换为使用 多重处理

这将导致某种“ 时间流”, 因为您正在使用 < code> sleep (如果独立运行,您的守护进程也会如此 ) 。 如果有必要, 您可以使用中断, 或者计算直到下一个五分钟的多分钟时间, 而不是只睡五分钟 。

问题回答

如果您的延迟时间较长, 不一定要准时执行, 您可以使用一个简单的累积器来跟踪短动作数个周期所用的时间。 如果 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




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签