Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

background

Regular tasks are often used in our actual development, such as Linux Corntab, Django-celery, Django-corntab, etc. However, these tools and frameworks have some inappropriateness, such as inflexibility, unwieldy, etc. Today we will introduce a lightweight Schedule task framework.

About the Schedule

Lightweight, zero dependence, simplicity and easy to use are all advantages of Schedule.

The installation

pip install schedule

example

import schedule,time

def job() :
    print("I'm working...")

Execute every 10 minutes
schedule.every(10).minutes.do(job)

Execute every one hour interval
schedule.every().hour.do(job)

Run this command every day at 18:50
schedule.every().day.at("18:50").do(job)

# Execute once every Monday
schedule.every().monday.do(job)

Execute once every week at 18:50 on Sunday
schedule.every().sunday.at("18:50").do(job)

Every Wednesday at 18:50
schedule.every().wednesday.at("18:50").do(job)

Run this command at the 44th second of every minute
schedule.every().minute.at(44 ":").do(job)

n=0
while True:
    schedule.run_pending()
    time.sleep(1)
    n=n+1
    if n>=120:
        break
Copy the code

The above is the most basic usage of schedule, which I have annotated. According to the preceding rules, the scheduled task will trigger four times. Because today is Sunday, xiaobian triggers scheduled tasks at 18:49:33, so the scheduled tasks will be executed at 18:50 on Sunday and at 18:50 every day. The scheduled tasks will be triggered twice within 2 minutes for 44 seconds. So there are four jobs executed.

The practical application

As a simple and practical example, I plan to use a timed task to obtain the current temperature of Xi ‘an every two seconds for real-time observation. If you’re interested, consider visualizing it as well.

code

import schedule,time,requests,json

def job() :
    response_res = requests.get('http://api.k780.com/?app=weather.today&weaId=316&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json')
    response_res.raise_for_status
    weather_info = json.loads(response_res.content).get("result")
    citynm=weather_info.get("citynm")
    temperature_curr=weather_info.get("temperature_curr")
    print(F 'Current city:{citynm}The temperature at the moment is:{temperature_curr}')

Run this command every 2 seconds
schedule.every(2).seconds.do(job)

n=0
while True:
    schedule.run_pending()
    time.sleep(1)
    n=n+1
    if n>10:
        break
Copy the code

We timed it for 10 seconds and executed it once every 2 seconds. Unsurprisingly, we obtained the temperature of Xi ‘an for 5 times in our timed task. From the results, we know that the current outdoor temperature is 31℃, so we still suggest you to blow air conditioning at home.

That’s all for today, thank you for reading, and we’ll see you next time.