threading.Timer 模块需要建议

threading.Timer module need advice

我正在尝试制作一个执行计划备份的代码,它必须在将来的某个时间点执行(例如 10 秒后),我希望它在一段时间后(10 秒)再次执行.我发现 threading.Time 内置模块,它在运行一次后就停止了。我知道是我做错了所以请帮助我

import time
import shutil
from datetime import datetime, timedelta
from threading import Timer

# calculating 
x = datetime.today()
bkup = x.replace(second = x.second) + timedelta(seconds = 10)
delta_t=bkup-x
secs=int(delta_t.total_seconds())

# creating an archive
def backup():
    source = 'D:\py'
    target_dir = 'D:\Backup'

    b = '%Y{0}%m{0}%d{0}%H{0}%M{0}%S'.format('.')
    target = target_dir + os.sep + time.strftime(b)

    a = shutil.make_archive(target, 'zip', target_dir, source)

    if os.system(a) == 0:
        print('Backup success!', target)
    else:
        print('Backup fail')


t = Timer(secs, backup)
t.start()



计时器只运行一次。你可以:

  • 备份完成后启动一个新计时器

  • 在计时器函数中创建一个 while 循环

  • 使用您的操作系统开始备份。在 linux 中,这可以通过 cron job 完成,在 windows 中使用任务调度程序

另见 this 问题。

将你的备份代码放在一个单独的线程中,然后有一个无限的 while 循环,它根据你的等待间隔等待。我在下面附上了代码。

import os
import sys
import shutil
from threading import Thread
import time


class BackupUtil(Thread):
    def __init__(self, interval, src_path, dst_path):
        super().__init__()
        self.interval = interval
        self.src_path = src_path
        self.dst_path = dst_path

    def run(self):
        while True:
            b = '%Y{0}%m{0}%d{0}%H{0}%M{0}%S'.format('.')
            target = self.dst_path + os.sep + time.strftime(b)
            archive = shutil.make_archive(target, 'zip', self.src_path, self.dst_path)

            if os.path.exists(archive):
                print('Backup success!', target)
            else:
                print('Backup failed.')
            time.sleep(self.interval)

if __name__ == '__main__':
    src = sys.argv[1] if os.path.exists(sys.argv[1]) else os.path.join('D', 'py')
    dst = sys.argv[2] if os.path.exists(sys.argv[2]) else os.path.join('D', 'Backup')
    backup = BackupUtil(10, src, dst)
    backup.start()

或者,如果您正在 linux 或 运行 宁 WSL,您可以将其设置为 运行 作为 cron 工作。添加一个 python shebang 到你的脚本 #!/usr/bin/env python3 然后将你的备份脚本保存到类似 /mnt/c/py/backup_archive 我更喜欢删除 .py 扩展名这样我们就可以很容易地告诉脚本是为了可执行。最后,确保它实际上是可执行的(chmod +x /mnt/c/py/backup_archivechmod 775 /mnt/c/py/backup_archive)。

#!/usr/bin/env python3


import os
import sys
import shutil
from threading import Thread
import time


class BackupUtil(Thread):
    def __init__(self, interval, src_path, dst_path):
        super().__init__()
        self.interval = interval
        self.src_path = src_path
        self.dst_path = dst_path

    def run(self):
        while True:
            b = '%Y{0}%m{0}%d{0}%H{0}%M{0}%S'.format('.')
            target = self.dst_path + os.sep + time.strftime(b)
            archive = shutil.make_archive(target, 'zip', self.src_path, self.dst_path)

            if os.path.exists(archive):
                print('Backup success!', target)
            else:
                print('Backup failed.')
            time.sleep(self.interval)

if __name__ == '__main__':
    src = sys.argv[1] if os.path.exists(sys.argv[1]) else os.path.join('D', 'py')
    dst = sys.argv[2] if os.path.exists(sys.argv[2]) else os.path.join('D', 'Backup')
    backup = BackupUtil(10, src, dst)
    backup.start()

然后为脚本添加一个cron作业,将间隔设置为1分钟(默认情况下不会小于1分钟间隔,也觉得没有必要)。

crontab -e
1 * * * * /mnt/c/py/backup_archive arg1 arg2