As a little programmer in my programming field, I am currently working as team lead in an entrepreneurial team. The technology stack involves Android, Python, Java and Go, which is also the main technology stack of our team. Contact: [email protected]

Recently, I often use the scheduled task when doing projects. Since my project is developed using Java and uses the SpringBoot framework, it is not difficult to implement the scheduled task.

Then I thought if I were to implement it in Python, how would I do it? The first thing that came to my mind was Timer

0x00 Timer

This is a timed task that extends from the threading module. It’s actually a thread.


Start by defining a method that needs to be executed periodically
>>> def hello(a):
	print("hello!")

# Import threading and create Timer. Set the hello method to execute after 1 second
>>> import threading
>>> timer = threading.Timer(1,hello)
>>> timer.start()
Print after 1 second
>>> hello!
Copy the code

The built-in tool is also simple to use and very easy for those of you who are familiar with Java. But can I always have a more Pythonic tool or library?

When I saw an article about the use of the Scheduler library, I suddenly thought this was what I wanted

0x01 Scheduler

To use the library, install it using the following command

pip install schedule
Copy the code

The methods in the Schedule module are very readable and support chained calls

import schedule

Define the methods that need to be executed
def job(a):
    print("a simple scheduler in python.")

Set the scheduling parameters, in this case, every 2 seconds
schedule.every(2).seconds.do(job)

if __name__ == '__main__':
    while True:
        schedule.run_pending()

# Execution result
a simple scheduler in python.
a simple scheduler in python.
a simple scheduler in python.
...
Copy the code

Other methods for setting scheduling parameters

Execute every hour
schedule.every().hour.do(job)
# Execute at 12:25 every day
schedule.every().day.at("The word").do(job)
Execute every 2 to 5 minutes
schedule.every(5).to(10).minutes.do(job)
# Every 4 at 19:15
schedule.every().thursday.at("19:15").do(job)
Every 17 minutes
schedule.every().minute.at(", 17").do(job)
Copy the code

What if the method to be executed requires parameters?

The method that needs to be executed needs to be passed
def job(val):
    print(f'hello {val}')


# schedule.every(2).seconds.do(job)
Use the do method with arguments
schedule.every(2).seconds.do(job, "hylinux")

# Execution result
hello hylinux
hello hylinux
hello hylinux
hello hylinux
hello hylinux
hello hylinux
...
Copy the code

Isn’t that easy?

0x02 Learning Materials

  1. Bhupeshv. Me/A – Simple – Sc…