How to schedule code execution in Python?

Viewed 313

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?

2 Answers

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')

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.

Related