0

我开始学习 Python(新手),所以对不同的模块等不太了解。

我要模拟的场景:

我有一个程序prg1.py,我想运行一些用户定义的时间,比如t秒。在这段时间(t秒)之后,程序应该退出。为此,我signal.signal()用来创建警报。下面是工作代码:

    进口信号
    进口时间
    导入系统

    def 接收警报(信号,堆栈):
        sys.exit('退出!')

    signal.signal(signal.SIGALRM,receive_alarm)
    信号.警报(10)

    而1:
    打印'工作...'
    时间.sleep(1)

程序运行 10 秒,然后按预期退出。
注意:下面的 while 循环仅用于测试,它将被我的工作代码替换。

现在我想实现多个信号以在不同的时间间隔执行不同的任务。

eg In EVERY:
5seconds: 执行特定的函数fun1()
10seconds: 执行特定的函数fun2(), 依此类推...(我想在程序中执行的任务)

我尝试添加另一个警报,如下所示,但没有奏效:

import signal
import time
import sys

def receive_alarm(signum, stack):
    sys.exit('Exiting!')

def receive_alarm_two(signup, stack):
    print 'Call to other functions!'

signal.signal(signal.SIGALRM, receive_alarm)
signal.alarm(10)

# Second Alarm
signal.signal(signal.SIGALRM, receive_alarm_two)
signal.alarm(2)

while 1:
print 'Working...'
time.sleep(1)

这不行!简单退出,没有任何错误或退出消息:(

如何实现此功能?

笔记:Use of Threads is restricted.

笔记:As I want the program to keep listening to different signals, it can't sleep i.e. cannot use time.sleep().

4

1 回答 1

2

您应该查看模块是否可以满足您的要求sched;另外,为什么不允许多线程?

通过在计划事件期间的最大公约数的时间间隔发生警报,​​可以使用单个警报安排多个任务。下面是一个例子,但它不是很健壮,例如,如果任何任务需要很长时间,时间就会不准确。这是可以修复的(使用 跟踪时间time.time(),并相应地安排下一个警报),但仍然存在其他问题(如果一个任务运行时间过长以至于下一个任务开始较晚会发生什么?)。我的看法是调度程序是许多棘手的极端情况的问题,如果可能的话,您应该使用现有的解决方案,而不是自己编写解决方案。

import signal
import time

class Scheduler(object):
    """Trivial scheduler object.

    Rather use sched.scheduler"""

    def __init__(self):
        self._tasks= [(1,self._heartbeat)]
        self._tick= 0
        self.stopped=False

    def addtask(self,period,task):
        """Add a task to be executed every PERIOD seconds

        addtask(period,task)

        period: seconds
        task: callable taking 'tick' argument
        """
        self._tasks.append( (period,task) )

    def _heartbeat(self,tick):
        print 'heartbeat: %d' % tick

    def _execute(self,signum,stack):
        if self.stopped:
            return

        self._tick += 1
        for period, task in self._tasks:
            if 0==self._tick % period:
                task(self._tick)
        signal.alarm(1)

    def start(self):
        signal.signal(signal.SIGALRM, self._execute)
        signal.alarm(1)

    def stop(self):
        self.stopped=True

class Stopper(object):
    """Callable to stop a scheduler"""
    def __init__(self, scheduler):
        self._scheduler=scheduler

    def __call__(self,tick):
        print 'stopping at tick',tick
        self._scheduler.stop()

def task3s(tick):
    print '3s task at tick',tick

def task7s(tick):
    print '7s task at tick',tick

s= Scheduler()
s.addtask(10,Stopper(s))
s.start()

s.addtask(3,task3s)
s.addtask(7,task7s)

while not s.stopped:
    time.sleep(0.5)
    print 'mainloop...'

在我的(python2)系统上,这给出了:

mainloop...
heartbeat: 1
mainloop...
mainloop...
heartbeat: 2
mainloop...
mainloop...
heartbeat: 3
3s task at tick 3
mainloop...
mainloop...
heartbeat: 4
mainloop...
mainloop...
heartbeat: 5
mainloop...
mainloop...
heartbeat: 6
3s task at tick 6
mainloop...
mainloop...
heartbeat: 7
7s task at tick 7
mainloop...
mainloop...
heartbeat: 8
mainloop...
mainloop...
heartbeat: 9
3s task at tick 9
mainloop...
mainloop...
heartbeat: 10
stopping at tick 10
mainloop...
于 2014-05-07T09:36:47.007 回答