Put your backup code in a separate thread and then have an infinite while loop which waits based on your wait interval. I've attached code down below.
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()
Alternatively, if you are on linux or running WSL
, you can set this to run as a cron
job. Add a python shebang to your script #!/usr/bin/env python3
then save your backup script to something like /mnt/c/py/backup_archive
I prefer to remove the .py
extension so we can easily tell the script is meant to be executable. Lastly, make sure it's actually executable (chmod +x /mnt/c/py/backup_archive
or chmod 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()
Then add a cron job for the script, setting the interval to 1 minute (doesn't do less than 1 minute intervals by default, don't really think that's necessary either).
crontab -e
1 * * * * /mnt/c/py/backup_archive arg1 arg2