|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162 |
- from celery_app import celery_app
- from fastapi import Request,FastAPI
- import time,datetime
- from celery import Celery
- import celery.schedules
- from redbeat import RedBeatSchedulerEntry
- from datetime import timedelta
-
- from services.redis_service import RedisService
- from services.kafka_service import KafkaService
- from services.gewe_service import GeWeService
-
- from common.utils import *
- import asyncio,random
- from model.models import AddGroupContactsHistory
- import logging
- from model.models import AgentConfig
-
- import logging
- import sys,traceback
-
- logger = logging.getLogger('redbeat')
-
-
- @celery_app.task(name='tasks.add_task', bind=True, acks_late=True)
- def add_task(self, x, y):
-
- time.sleep(5)
- logger.info('add')
- return x + y
-
-
- @celery_app.task(name='tasks.mul_task', bind=True, acks_late=True)
- def mul_task(self, x, y):
- time.sleep(5)
- return x * y
-
-
-
-
-
-
-
-
-
- @celery_app.task(name='tasks.sync_contacts', bind=True, acks_late=True)
- async def sync_contacts_task(self, redis_service):
-
- login_keys = list(await redis_service.client.scan_iter(match='__AI_OPS_WX__:LOGININFO:*'))
- return login_keys
-
-
- @celery_app.task(name='tasks.background_worker_task', bind=True, acks_late=True)
- def background_worker_task(self, redis_config, kafka_config, gewe_config):
- async def task():
- redis_service = RedisService()
- await redis_service.init(**redis_config)
- login_keys = []
- async for key in redis_service.client.scan_iter(match='__AI_OPS_WX__:LOGININFO:*'):
- login_keys.append(key)
- print(login_keys)
-
- asyncio.run(task())
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- @celery_app.task(name='tasks.scheduled_task_sync_wx_info', bind=True, acks_late=True)
- def scheduled_task_sync_wx_info(self, redis_config, kafka_config, gewe_config):
- '''
- 定时获取微信号资料
- '''
- async def process_key(redis_service, gewe_service, semaphore, key):
- async with semaphore:
- try:
- r = await redis_service.get_hash(key)
- app_id = r.get("appId")
- token_id = r.get("tokenId")
- wxid = r.get("wxid")
- status = r.get('status')
- if status == '0':
- logger.warning(f"微信号 {wxid} 已经离线")
- return
- ret, msg, profile = await gewe_service.get_profile_async(token_id, app_id)
- if ret != 200:
- logger.warning(f"同步微信号 {wxid} 资料失败: {ret}-{msg}")
- return
- nickname = profile.get("nickName")
- head_img_url = profile.get("smallHeadImgUrl")
- r.update({"nickName": nickname, "headImgUrl": head_img_url, "modify_at": int(time.time())})
- cleaned_login_info = {k: (v if v is not None else '') for k, v in r.items()}
- await redis_service.set_hash(key, cleaned_login_info)
- logger.info(f"定时同步微信号{wxid}-昵称{nickname} 资料成功")
- except Exception as e:
- logger.error(f"处理键 {key} 时发生异常: {e}")
-
- async def task():
- try:
- redis_service = RedisService()
- await redis_service.init(**redis_config)
- gewe_service = await GeWeService.get_instance(redis_service, gewe_config['api_url'])
- login_keys = []
- async for key in redis_service.client.scan_iter(match='__AI_OPS_WX__:LOGININFO:*'):
- login_keys.append(key)
-
-
- semaphore = asyncio.Semaphore(10)
-
- await asyncio.gather(*[process_key(redis_service, gewe_service, semaphore, key) for key in login_keys])
- except Exception as e:
- logger.error(f"任务执行过程中发生异常: {e}")
-
- loop = asyncio.get_event_loop()
- if loop.is_closed():
- loop = asyncio.new_event_loop()
- asyncio.set_event_loop(loop)
- loop.run_until_complete(task())
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- @celery_app.task(name='tasks.scheduled_task_add_contacts_from_chatrooms', bind=True, acks_late=True)
- def scheduled_task_add_contacts_from_chatrooms(self, redis_config, kafka_config, gewe_config):
-
- '''
- 关于群加好友的请求规则: 每个智能体一次最多30人,间隔2小时做1次,即最多90人/天。
- 加好友规则:每天处理次数、间隔时间(分钟)、每次加好友人数这3个参数都可以设置。目前默认只是上面的设置。
- '''
- async def process_login_key(redis_service:RedisService, gewe_service: GeWeService, kafka_service:KafkaService, k, gewe_config, oneday_add_contacts_total, once_add_contacts_total, semaphore):
- async with semaphore:
- try:
- r = await redis_service.get_hash(k)
- app_id = r.get("appId")
- token_id = r.get("tokenId")
- wxid = r.get("wxid")
- status = r.get('status')
-
- if status == '0':
- logger.warning(f"微信号 {wxid} 已经离线,群成员不能定时添加")
- return
-
- config = await gewe_service.get_wxchat_config_from_cache_async(wxid)
- validated_config = AgentConfig.model_validate(config)
- if not validated_config.agentEnabled:
- logger.warning(f"微信号 {wxid} 取消了托管,群成员不能定时添加")
- return
-
-
- is_wx_expection = await gewe_service.get_wx_expection_async(wxid, "addGroupMemberAsFriend")
- if is_wx_expection:
- logger.info(f"{wxid} 本次任务接口addGroupMemberAsFriend异常, {is_wx_expection},本次群好友邀请任务未开始,跳过任务。")
- return
-
- cache_task_run_time_wxid_logs = await gewe_service.get_task_run_time_by_wxid_async(wxid, 'scheduled_task_add_contacts_from_chatrooms')
- if cache_task_run_time_wxid_logs:
- sorted_tasks = sorted(cache_task_run_time_wxid_logs, key=lambda x: x.get("runTime"), reverse=True)
- last_run_time = sorted_tasks[0].get("runTime")
- if last_run_time > 1e12:
- last_run_time = last_run_time / 1000
-
-
- last_run_time = datetime.fromtimestamp(last_run_time)
-
-
- current_time = datetime.now()
-
-
- time_difference = current_time - last_run_time
-
-
- if time_difference < timedelta(hours=2):
- logger.info(f"{wxid}上次定时群成员定时添好友任务在2小时内,不再执行")
- return
-
- cache_task_run_time_wxid_logs.append({"runTime": int(time.time())})
- await gewe_service.save_task_run_time_by_wxid_async(wxid, 'scheduled_task_add_contacts_from_chatrooms', cache_task_run_time_wxid_logs, 3600 * 2)
- c:dict = await gewe_service.get_wxchat_config_from_cache_async(wxid)
- contacts = await gewe_service.get_contacts_brief_from_cache_async(wxid)
-
- contact_wxids = [c.get('userName') for c in contacts]
- chatrooms = c.get('addContactsFromChatroomIdWhiteList', [])
- logger.info(f'{wxid} 定时群成员定时添好友任务开始')
- wixd_add_contacts_from_chatrooms_times = {wxid: 0}
- for chatroom_id in chatrooms:
- chatroom = await gewe_service.get_group_info_from_cache_async(wxid, chatroom_id)
- chatroom_member = await gewe_service.get_group_members_from_cache_async(wxid, chatroom_id)
-
- chatroom_nickname = chatroom.get('nickName')
- chatroom_owner_wxid = chatroom_member.get('chatroomOwner', None)
- admin_wxids = chatroom_member.get('adminWxid', [])
- admin_wxids = chatroom_member.get('adminWxid')
- if admin_wxids is None:
- admin_wxids = []
-
- logger.info(f'{chatroom_nickname} 的群主是 {chatroom_owner_wxid},管理员是{admin_wxids}')
- contact_wxids_set = set(contact_wxids)
- if admin_wxids:
- contact_wxids_set.update(set(admin_wxids))
- if chatroom_owner_wxid is not None:
- contact_wxids_set.add(chatroom_owner_wxid)
-
- contact_wxids_set.add(wxid)
- unavailable_wixds = await gewe_service.check_wixd_group_add_contacts_history_async(wxid, chatroom_id)
- if unavailable_wixds:
- contact_wxids_set.update(set(unavailable_wixds))
-
- chatroom_member_list = chatroom.get('memberList', [])
- if chatroom_member_list is None:
- chatroom_member_list = []
- elif not isinstance(chatroom_member_list, list):
- chatroom_member_list = list(chatroom_member_list)
-
- remaining_chatroot_members = [x for x in chatroom_member_list if x.get('wxid') not in contact_wxids_set]
-
- nickname = next((member['nickName'] for member in chatroom_member_list if member['wxid'] == wxid), None)
- if not remaining_chatroot_members:
- logger.info(f'{nickname}-{wxid} 在 {chatroom_nickname}-{chatroom_id} 群里没有好友可以邀请')
-
- k_message = wx_add_contacts_from_chatroom_task_status_message(wxid, chatroom_id, 2)
- await kafka_service.send_message_async(k_message)
- continue
-
- logger.info(f'{nickname}-{wxid} 在 {chatroom_nickname} 群里还可以邀请的好友有:{[x.get("nickName") for x in remaining_chatroot_members]}')
- for m in remaining_chatroot_members:
-
- if wixd_add_contacts_from_chatrooms_times[wxid] == once_add_contacts_total:
- logger.info(f"{wxid} 本次任务已经邀请了{once_add_contacts_total}人,不再邀请")
- return
-
-
- is_add_group_times = await gewe_service.is_group_add_contacts_history_one_day_async(wxid, oneday_add_contacts_total)
- if is_add_group_times:
- logger.info(f"当天 {wxid} 所有群的成员已经加了{oneday_add_contacts_total}个好友,不再添加")
- return
-
-
- is_wx_expection = await gewe_service.get_wx_expection_async(wxid, "addGroupMemberAsFriend")
- if is_wx_expection:
- logger.info(f"{wxid} 本次任务接口addGroupMemberAsFriend异常,不再邀请,{is_wx_expection}")
- return
-
- contact_wxid = m.get('wxid')
- member_nickname = m.get("nickName")
- group_add_contacts_history = await gewe_service.get_group_add_contacts_history_async(wxid, chatroom_id, contact_wxid)
-
- if group_add_contacts_history:
- sorted_history = sorted(group_add_contacts_history, key=lambda x: x.addTime, reverse=True)
-
-
- if len(sorted_history) == 2:
- logger.info(f'{nickname}-{wxid}在{chatroom_nickname}-{chatroom_id} 群的 {member_nickname}-{contact_wxid} 已经邀请过2次,不再邀请')
- continue
-
-
- if len(sorted_history) > 0:
- last_add_time = sorted_history[0].addTime
-
- def is_add_time_more_than_one_day(addTime: int) -> bool:
- """
- 判断 addTime 是否与当前时间相隔大于 3600 × 24 秒
- :param addTime: Unix 时间戳
- :return: 如果 addTime 与当前时间相隔大于 3600 × 24 秒,返回 True;否则返回 False
- """
-
- current_time = time.time()
-
-
- time_difference = abs(current_time - addTime)
-
-
- return time_difference > 3600 * 24
-
- is_more_than_one_day = is_add_time_more_than_one_day(last_add_time)
- if not is_more_than_one_day:
- logger.info(f'{nickname}-{wxid}在{chatroom_nickname}-{chatroom_id} 群的 {member_nickname}-{contact_wxid} 已经24小时邀请,不再邀请')
- continue
-
- ret, msg, data = await gewe_service.add_group_member_as_friend_async(token_id, app_id, chatroom_id, m.get('wxid'),
- f'我是群聊"{chatroom_nickname}"群的{nickname}')
-
- history = AddGroupContactsHistory.model_validate({
- "chatroomId": chatroom_id,
- "wxid": wxid,
- "contactWixd": contact_wxid,
- "addTime": int(time.time())
- })
-
- if ret != 200:
- logger.warning(f'{nickname}-{wxid} 在 {chatroom_nickname}-{chatroom_id} 群好友 {member_nickname}-{contact_wxid} 邀请失败原因:{ret} {msg} {data}')
-
- if data and '操作过于频繁' in data.get('msg', ''):
- await gewe_service.save_wx_expection_async(wxid, "addGroupMemberAsFriend", msg, today_seconds_remaining())
- await gewe_service.save_group_add_contacts_history_async(wxid, chatroom_id, contact_wxid, history)
- logger.warning(f'{nickname}-{wxid} 在 {chatroom_nickname}-{chatroom_id} 群的 {member_nickname}-{contact_wxid} 操作过于频繁,本次群好友邀请任务未完成跳过。当天不再处理该号群好友邀请任务')
- return
-
-
- await gewe_service.save_group_add_contacts_history_async(wxid, chatroom_id, contact_wxid, history)
- wixd_add_contacts_from_chatrooms_times[wxid] += 1
- logger.info(f'{nickname} 向 {chatroom_nickname}-{chatroom_id} 群的 {m.get("nickName")}-{m.get("wxid")} 发送好友邀请 {msg} \n {data} \n 当前已邀请好友数:{wixd_add_contacts_from_chatrooms_times[wxid]}')
-
- k_message = wx_add_contacts_from_chatroom_message(history.wxid, history.chatroomId, history.contactWixd, history.addTime)
- await kafka_service.send_message_async(k_message)
-
-
- await asyncio.sleep(random.uniform(270,300))
-
- task_status = await gewe_service.wx_add_contacts_from_chatroom_task_status_async(wxid, chatroom_id)
- k_message=wx_add_contacts_from_chatroom_task_status_message(wxid, chatroom_id, task_status)
- await kafka_service.send_message_async(k_message)
-
- await asyncio.sleep(random.uniform(1.5, 3))
- except Exception as e:
-
- tb = sys.exc_info()[2]
-
- e = e.with_traceback(tb)
-
- logger.error(f"任务执行过程中发生异常: {e}\n异常类型: {type(e).__name__}\n异常信息: {str(e)}\n堆栈跟踪: {traceback.format_exc()}")
-
- async def task():
- try:
- now = datetime.now()
-
-
-
-
- if now.hour < 8 or now.hour > 22:
- logger.info(f"定时群成员定时添好友任务不启动, 当前时间为 {now.strftime('%Y-%m-%d %H:%M:%S')},不在8点到22点之间")
- return
-
- logger.info('定时群成员定时添好友任务开始')
- redis_service = RedisService()
- await redis_service.init(**redis_config)
- gewe_service = await GeWeService.get_instance(redis_service, gewe_config['api_url'])
- KAFKA_BOOTSTRAP_SERVERS = kafka_config['bootstrap_servers']
- KAFKA_TOPIC = kafka_config['topic']
- KAFKA_GROUP_ID = kafka_config['group_id']
-
- kafka_service = KafkaService(KAFKA_BOOTSTRAP_SERVERS, KAFKA_TOPIC, KAFKA_TOPIC, KAFKA_GROUP_ID)
- await kafka_service.start_producer()
- global_config = await gewe_service.get_global_config_from_cache_async()
- scheduled_task_add_contacts_from_chatrooms_config = global_config.get('scheduledTaskAddContactsFromChatrooms', {})
-
- oneday_add_contacts_total = 90
- once_add_contacts_total = 30
-
- if scheduled_task_add_contacts_from_chatrooms_config:
- oneday_add_contacts_total = scheduled_task_add_contacts_from_chatrooms_config.get('oneDayAddContactsTotal', 90)
- once_add_contacts_total = scheduled_task_add_contacts_from_chatrooms_config.get('onceAddContactsTotal', 30)
-
-
- login_keys = []
- async for key in redis_service.client.scan_iter(match='__AI_OPS_WX__:LOGININFO:*'):
- login_keys.append(key)
-
-
- semaphore = asyncio.Semaphore(10)
-
- await asyncio.gather(*[process_login_key(redis_service, gewe_service, kafka_service, k, gewe_config, oneday_add_contacts_total, once_add_contacts_total, semaphore) for k in login_keys])
-
- except Exception as e:
-
- tb = sys.exc_info()[2]
-
- e = e.with_traceback(tb)
-
- logger.error(f"任务执行过程中发生异常: {e}\n异常类型: {type(e).__name__}\n异常信息: {str(e)}\n堆栈跟踪: {traceback.format_exc()}")
- finally:
- await kafka_service.stop_producer()
-
- loop = asyncio.get_event_loop()
- if loop.is_closed():
- loop = asyncio.new_event_loop()
- asyncio.set_event_loop(loop)
- loop.run_until_complete(task())
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- REDIS_KEY_PATTERN = "friend_add_limit:{date}"
- REDIS_LAST_RUN_KEY = "last_run_time:add_friends_task"
-
- @celery_app.task(name='tasks.add_friends_task', bind=True, acks_late=True)
- def add_friends_task(self,redis_config):
- """
- 限制每天最多 15 个,每 2 小时最多 8 个
- """
- async def task():
- redis_service = RedisService()
- await redis_service.init(**redis_config)
- today_str = datetime.now().strftime("%Y%m%d")
- redis_key = REDIS_KEY_PATTERN.format(date=today_str)
-
-
- total_added = await redis_service.get_hash_field(redis_key, "total") or 0
- last_2h_added =await redis_service.get_hash_field(redis_key, "last_2h") or 0
-
- total_added = int(total_added)
- last_2h_added = int(last_2h_added)
-
- logger.info(f"当前添加好友总数: {total_added}, 过去2小时添加: {last_2h_added}")
-
-
- if total_added >= 15:
- logger.warning("今日好友添加已达上限!")
- return
-
- if last_2h_added >= 8:
- logger.warning("过去2小时添加已达上限!")
- return
-
-
- max_add = min(15 - total_added, 8 - last_2h_added)
- if max_add <= 0:
- return
-
- num_to_add = min(max_add, 1)
- logger.info(f"本次添加 {num_to_add} 位好友")
-
-
-
-
- success = num_to_add
-
-
- if success > 0:
- await redis_service.increment_hash_field(redis_key, "total", success)
- await redis_service.increment_hash_field(redis_key, "last_2h", success)
-
-
- await redis_service.expire(redis_key, 86400)
- await redis_service.expire_field(redis_key, "last_2h", 7200)
-
- logger.info(f"成功添加 {success} 位好友, 今日总数 {total_added + success}")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- loop = asyncio.get_event_loop()
-
- if loop.is_closed():
- loop = asyncio.new_event_loop()
- asyncio.set_event_loop(loop)
-
- loop.run_until_complete(task())
-
- def today_seconds_remaining()->int:
- current_time = datetime.now()
-
-
- end_of_day = datetime(current_time.year, current_time.month, current_time.day, 23, 59, 59)
-
-
- time_difference = end_of_day - current_time
-
-
- time_difference_seconds = int(time_difference.total_seconds())
-
- return time_difference_seconds
-
-
- @celery_app.task(name='tasks.random_scheduled_task', bind=True, acks_late=True)
- def random_scheduled_task(self,):
- print(f"Task executed at {datetime.now()}")
-
- next_run_in = random.randint(10, 60)
- print(f"Next execution will be in {next_run_in} seconds")
-
-
- entry = RedBeatSchedulerEntry(
- name='random-task',
- task='tasks.random_scheduled_task',
- schedule=timedelta(seconds=next_run_in),
- app=celery_app
- )
- entry.save()
- return f"Scheduled next run in {next_run_in} seconds"
-
|