5

I have a function that is running inside a for loop. My goal is to run it every day at a specific time, such as 10 am.

My code is:

def get_sql_backup_transfer(ip, folder,path_sec_folder,sec_folder,path):
    call(["robocopy",f'{ip}\\{folder}', f'{path_sec_folder}{sec_folder}',"/tee","/r:5","/w:120","/S","/MIR",f"/LOG:{path}{sec_folder}.log"])


for i in sqlserverList :
    get_sql_backup_transfer(i['ip'] , i['folder'] , path_sec_folder ,i['sec_folder'] , path )

How can I run this code automatically every day at 10 am?

mzjn
  • 48,958
  • 13
  • 128
  • 248
ashkan
  • 530
  • 3
  • 11
  • 5
    If it were me, I'd be using `cron` or Task Scheduler, tools already built for the job, to run the python script at the needed times. – Ouroborus Jan 22 '22 at 08:09
  • 1
    Do you think I should use operating system tools? – ashkan Jan 22 '22 at 08:13
  • 2
    Using operating tools, e.g. `cron`, is much easier than setting up a periodic task from Python. If you want to use Python then it can be done with [celery](https://docs.celeryproject.org/en/stable/userguide/periodic-tasks.html). – liveware Jan 22 '22 at 08:25

2 Answers2

2

There are some ways to do this , but the best way is using 'schedule' package, i guess
However, in the first step install the package :

pip install schedule

And then use it in your code like the following codes :

import schedule

schedule.every().day.at("10:00").do(yourFunctionToDo,'It is 10:00')
Hamid
  • 239
  • 3
  • 12
1

Most operating systems in use today already have a service for that:

  • schtasks.exe (Task Scheduler) on ms-windows.
  • cron on UNIX-like systems such as Linux and *BSD.
  • launchd on macOS (although cron should also work).

Unless these cannot meet your need for whatever reason, I'd suggest using this in favor of writing your own.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94