Python: Celery+Redis implements timing tasks

Summary : Celery is a Python-based task queue library that provides a convenient way to execute periodic or delayed tasks in asynchronous processing applications. Celery timing task is an important function provided by Celery, which allows developers to schedule and execute periodic tasks in a simple and reliable way.

History Raiders:

Python: Celery+Redis+Flower installation and use

Case source code:

# -*- coding: utf-8 -*-
# time: 2023/4/16 11:23
# file: tasks.py
# 公众号: 玩转测试开发
import datetime
from celery import Celery
from celery.schedules import crontab

# 连接远程redis服务的地址和端口号
redis_host = '111.112.113.114'  # 你的redis服务ip
redis_port = '6379'

app = Celery('tasks', broker=f'redis://{
      
      redis_host}:{
      
      redis_port}/0', backend=f'redis://{
      
      redis_host}:{
      
      redis_port}/1')


@app.task
def add(x, y):
    return x + y


@app.task
def subtract(x, y):
    return x - y


@app.task
def print_message():
    print(f'The time is now {
      
      datetime.datetime.now()}')


app.conf.beat_schedule = {
    
    
    'print-every-minute': {
    
    
        'task': 'tasks.print_message',
        'schedule': crontab(minute='*'),
    },
}

Running steps : Start a worker and a Beat daemon respectively, and the scheduled task will start running.

Start Celery workers

celery -A tasks worker --loglevel=info  -P eventlet

Start the Celery Beat daemon:

celery -A tasks beat --loglevel=info

operation result:

picture

Guess you like

Origin blog.csdn.net/hzblucky1314/article/details/130355741