在运行python脚本后增加睡眠时间

时间:2018-12-07 21:13:01

标签: python multithreading concurrency sleep python-multithreading

我有一个简单的python代码。它产生了一些东西,它睡了x秒,然后又产生了另一件事。我想在执行文件后延长睡眠时间。

例如

print("A")
time.sleep(x)
print("B")

执行代码后,我想在打印B之前更改并增加睡眠时间。

有可能吗?请帮忙。谢谢。

2 个答案:

答案 0 :(得分:0)

#!/usr/bin/env python

import time

try:
    with open(".sleeptime") as f:
        sleep_time = float(f.read())
except FileNotFoundError:
    sleep_time = 5.0

with open(".sleeptime", "w") as f:
    next_sleep_time = sleep_time + 5.0
    f.write(str(next_sleep_time))

print("A")
time.sleep(sleep_time)
print("B")

答案 1 :(得分:0)

此解决方案使用的是带有睡眠时间的列表,您可以在目标函数处于睡眠状态时通过附加更多睡眠来扩展睡眠时间。函数sleep_all会弹出并执行该列表中所有可用的睡眠。

import time
from datetime import datetime
from threading import Thread, current_thread


def f():
    print(f'{datetime.now()}: A')
    sleep_all()
    print(f'{datetime.now()}: B')


def sleep_all():
    sleeps = current_thread().sleeps
    while sleeps:
        sleep = sleeps.pop()
        print(f'{datetime.now()}: taking a nap for {sleep} s')
        time.sleep(sleep)


if __name__ == '__main__':


    t = Thread(target=f)
    t.sleeps = [5]  # attach instance attribute with sleeps-list
    t.start()
    time.sleep(2)
    print(f'{datetime.now()}: adding another sleep')
    t.sleeps.append(5)

示例输出:

2018-12-07 22:54:09.733494: A
2018-12-07 22:54:09.733553: taking a nap for 5 s
2018-12-07 22:54:11.735635: adding another sleep
2018-12-07 22:54:14.734963: taking a nap for 5 s
2018-12-07 22:54:19.738833: B

Process finished with exit code 0

带有子类Thread的版本:

import time
from datetime import datetime
from threading import Thread


class Program(Thread):

    def __init__(self, sleep=None):
        super().__init__()
        self._sleeps = [sleep]

    def run(self):
        print(f'{datetime.now()}: A')
        self._sleep_all()
        print(f'{datetime.now()}: B')

    def add_sleep(self, sleep):
        self._sleeps.append(sleep)

    def _sleep_all(self):
        while self._sleeps:
            sleep = self._sleeps.pop()
            print(f'{datetime.now()}: taking a nap for {sleep} s')
            time.sleep(sleep)


if __name__ == '__main__':

    prg = Program(sleep=5)
    prg.start()
    time.sleep(2)
    print(f'{datetime.now()}: adding another sleep')
    prg.add_sleep(sleep=5)
    prg.join()