0

Hi I have successfully scheduled a python job by using the below mentioned code

import schedule
import time

def job():
    print("I am doing this job!")


schedule.every().monday.at("14:00").do(job)
schedule.every().tuesday.at("14:00").do(job)
schedule.every().wednesday.at("14:00").do(job)
schedule.every().thursday.at("14:00").do(job)
schedule.every().friday.at("14:00").do(job)

while True:
    schedule.run_pending()
    time.sleep(1)

Now I need to implement the schedule only in Asia/Kolkata time zone. Can we use pytz library with this?

  • Yes and no. In the absence of any additional configuration, the jobs will run in whichever time zone the operating system is configured to use. – tripleee Mar 17 '22 at 06:46
  • How can I make it independent from the server? By hard coding the timezone in the python script itself? – Indrajit Mukherjee Mar 17 '22 at 07:13
  • You would have to _know_ the time zone of the server. A common convention is to always run servers in UTC, and then the rest will be easy; but without knowledge of how the server is configured, all we can really tell you is that the problem statement needs more details. – tripleee Mar 17 '22 at 07:18
  • Maybe this is a solution for you: https://stackoverflow.com/questions/47356453/python-schedule-jobs-with-different-timezones The [scheduler](https://github.com/DigonIO/scheduler) library for python offers support for this problem. – jpotyka Mar 19 '22 at 12:22

1 Answers1

0

If you absolutely must use schedule library and you want to work with different timezones, then you'll have to manually specify the time according to the time zone to schedule library.

    import schedule
    import time
    from datetime import datetime
    import pytz # you'll have to install pytz to get timezones

    def job():
        print("I am doing this job!")

    # Create a time zone object for Asia/Kolkata
    kolkata_tz = pytz.timezone('Asia/Kolkata')

    # Define the desired time for the job in Kolkata time
    job_time = datetime.now(kolkata_tz).replace(hour=14, minute=0, second=0, microsecond=0)

    # Schedule the job for each weekday at the specified time 
    schedule.every().monday.at(job_time.strftime("%H:%M")).do(job)

   schedule.every().tuesday.at(job_time.strftime("%H:%M")).do(job)

   schedule.every().wednesday.at(job_time.strftime("%H:%M")).do(job)

   schedule.every().thursday.at(job_time.strftime("%H:%M")).do(job)

   schedule.every().friday.at(job_time.strftime("%H:%M")).do(job)

    while True:
        schedule.run_pending()
        time.sleep(1)
Moses B
  • 1
  • 1