Preface

Previously, I published a Python script that needed to be placed on the server and sent daily at 6:00. At first, I used a very foolish method with a while loop and getting the current time, which caused my 2-core 4GB server's CPU to overload. So, I optimized it. Article address: Record of Python script

Optimization of Scheduled Tasks

I learned that Python has a scheduled task library schedule, which can help you create scheduled tasks and consumes very little resources. First, install the schedule library using pip.

pip install schedule

Then, follow these steps:

  1. Import the schedule library.
  2. Put the code to be executed at a specific time into a separate function.
  3. Use the schedule.every() function to set up scheduled tasks and use the .at() method to specify the execution time.
  4. Use the schedule.run_pending() function to check and run all pending tasks.

Example main_task is your task

import schedule
import time

def main_task():
    # Put the original scheduled task code here

if __name__ == '__main__':
    # Configure the logger
    # Set up the scheduled task
    schedule.every().day.at("07:35:30").do(main_task)
    while True:
        # Check and run all pending tasks
        schedule.run_pending()
        # Check every so often
        time.sleep(60)