定期在循环中输出统计数据

2024-04-26 13:51:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个经常使用daemon.runner运行的程序。它不断地处理来自stdin的数据,我使用syslog作为输出。你知道吗

代码如下所示:

class App():
  lines = 0

  def __init__(self):
    # Config

  def run(self):
    while True:
      with open(PIPE_NAME) as pipe:
        for line in pipe:
          # Do stuff
          self.lines = self.lines + 1

      # Reopen pipe if required (or die if it's unavailable)

我希望定期输出统计数据,例如每15分钟输出一次。我可以检查每次处理一行的时间,但是传入的数据项之间偶尔会有很大的间隙。你知道吗

有什么方法可以以固定的间隔定期输出这个例子中的self.lines?你知道吗


Tags: 数据代码self程序appifinitdef
2条回答

每一次迭代,都要检查自上次打印以来是否已经过了15分钟。如果是,打印并记录上次打印的时间。你知道吗

使用^{}循环以确保至少在每个打印间隔检查时间(本质上是“读取超时”):

import os
import select
import time

PRINT_INTERVAL = 15*60  # sec

def run():
    with open(PIPE_NAME) as pipe:
        last_print = 0
        while True:
            timeout = PRINT_INTERVAL - (time.time() - last_print)
            r,w,e = select.select([pipe], [], [], timeout)

            if pipe in r:
                # pipe is ready for reading
                handle_pipe(pipe)

            if (time.time() - last_print) > PRINT_INTERVAL:
                last_print = time.time()
                print_statistics()

def handle_pipe(pipe):
    for line in pipe:
       # Do stuff...

def print_statistics():
    print 'Statistics...'

您可以使用多线程:

import threading
import time

class App():
    lines = 0

    def __init__(self):
        # Config

    def run(self):
        myTimer = threading.Thread(target = self.timer)
        myTimer.start()

        while True:
            with open(PIPE_NAME) as pipe:
                for line in pipe:
                    # Do stuff
                    self.lines = self.lines + 1

            # Reopen pipe if required (or die if it's unavailable)

    def timer(self):
        start = time.time()
        while True:
            if time.time() - start > 900: # should be 15 minutes
                break

        print(self.lines)
        timer()

Multithreading is the ability of a program or an operating system to serve more than one user at a time and to manage multiple simultaneous requests without the need to have multiple copies of the programs running within the computer.

这个解决方案是快速的,不需要等待任何东西,它只是做它的工作,没有其他。我已经测试过一点了,但是如果有什么问题,就说出来。我真的希望这有帮助。:)

相关问题 更多 >