Celery periodic task not working with telebot

83 Views Asked by At

I have a Celery periodic task that is supposed to send a message every 2 minutes using the Telebot library. However, it doesn't seem to be working as expected. I have my Celery configuration in celery_config.py and the task definition in tasks.py.

Here's my code:

tasks.py:

from celery import Celery
import telebot
import time

bot = telebot.TeleBot("token")

app = Celery("tasks", broker="redis://localhost:6379/0")

user_data = {}

@app.task
def send_periodic_message():
    user_count = len(user_data)
    message_text = f"This is a periodic message sent every 2 minutes.\nTotal users: {user_count}"

    for user_id in user_data:
        bot.send_message(user_id, message_text)

if __name__ == "__main__":
    app.start()

celery_config.py:

from datetime import timedelta

CELERY_IMPORTS = ("tasks",)
CELERY_BROKER_URL = "redis://localhost:6379/0"
CELERY_RESULT_BACKEND = "redis://localhost:6379/0"
CELERYBEAT_SCHEDULE = {
    "send-periodic-message": {
        "task": "tasks.send_periodic_message",
        "schedule": timedelta(minutes=2),
    },
}

I've replaced 'token' with the actual token in my TeleBot instance. The Celery task is supposed to send a message every 2 minutes, but it doesn't seem to be working. What could be the issue here?

in terminal

[2024-02-23 13:50:30,423: INFO/SpawnPoolWorker-2] child process 6088 calling self.run()
[2024-02-23 13:50:30,606: INFO/SpawnPoolWorker-6] child process 6884 calling self.run()
[2024-02-23 13:50:33,619: INFO/SpawnPoolWorker-9] child process 7532 calling self.run()

Configured Celery with a Redis broker and backend using the celery_config.py file. Defined a Celery task in the tasks.py file named send_periodic_message, which sends a message using the Telebot library to each user in the user_data dictionary. Scheduled the send_periodic_message task to run every 2 minutes using Celery's beat scheduler. What I was expecting:

I was expecting the Celery periodic task (send_periodic_message) to run every 2 minutes and send a message to all users in the user_data dictionary using the Telebot library. The message should contain information about the total number of users.

If there are any issues, I would appreciate help in identifying and resolving them.

i'm tried these

celery -A tasks beat --loglevel=info
celery -A tasks worker --loglevel=info
celery -A celery_config beat --loglevel=info

0

There are 0 best solutions below