一、问题描述
在Linux系统的ECS云服务器上设置了crontab定时任务,期望每天都执行python文件,实际运行时只有每周六的定时任务执行失败
Linux定时任务执行日志如下:
Python脚本如下:
def send_msg_lucky(user):
content = lucky()
if content:
WeChatENT().send_msg(msg_type=1, user=user, text_content=content)
if __name__ == "__main__":
send_msg_lucky(user='user1,user2')
二、问题排查
Linux定时任务为每天的19:18执行python脚本,从执行日志可以看出服务器已经执行了命令
执行Python脚本时没有记录任何日志,很难排查问题所在,所以先给脚本添加日志
def send_msg_lucky(user):
log.info(f'{"==============>>>>"}开始发送幸运星')
try:
content = lucky()
if content:
TestENT().send_msg(msg_type=1, user=user, text_content=content)
log.info(f'{"==============<<<<"}幸运星发送成功,接收人:{user}')
else:
log.info(f'{"==============<<<<"}暂无幸运星')
except Exception as err:
info = f"出了点小问题!\n{err.args}\n{traceback.format_exc()}"
log.error(info)
log.info(f'{"==============<<<<"}幸运星发送失败')
if __name__ == "__main__":
send_msg_lucky(user='user1,user2')
修改后,2024.02.03(周六)运行生成日志如下:
从日志可以看出,问题出在date_handle这个脚本上
三、问题解决
date_handle脚本如下:
import datetime
weak_list = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
def solar_to_lunar(days=1):
tomorrow = (datetime.timedelta(days=days) + datetime.datetime.now()) # 明天的日期时间
year = tomorrow.year # 明天的年
month = tomorrow.month # 明天的月
weak = weak_list[tomorrow.weekday() + 1] # 明天的星期
return weak
weak = weak_list[tomorrow.weekday() + 1]:每到周六,从weak_list列表取值时会超下标。调整weak_list列表中的值并在取值时下标不加1,修改后的脚本如下:
import datetime
weak_list = ["周一", "周二", "周三", "周四", "周五", "周六", '周日']
def solar_to_lunar(days=1):
tomorrow = (datetime.timedelta(days=days) + datetime.datetime.now()) # 明天的日期时间
# tomorrow = (datetime.timedelta(days=days) + datetime.datetime.strptime('2024-02-3', '%Y-%m-%d'))
year = tomorrow.year # 明天的年
month = tomorrow.month # 明天的月
weak = weak_list[tomorrow.weekday()] # 明天的星期
print(weak)
return weak
if __name__ == "__main__":
solar_to_lunar()