OS_操作系统的CRONTAB 无法定时自动执行

前两日,客户要求我进行数据同步,我写好了脚本,设置了定时执行,让其在晚上后台自动执行,谁知第二天竟然没有执行。不得已又手动开始执行,

该问题已经遇到过多次,为了彻底解决该问题,今日对该现象进行了分析。

1.查看cron执行日志

查询 /var/adm/cron/log 报错如下:


! 0481-095 The cron job is being rescheduled.
 Mon Jan  4 14:35:00 BEIST 2016
! cron: 0481-087 The c queue maximum run limit has been reached.
 Mon Jan  4 14:35:00 BEIST 2016
! 0481-095 The cron job is being rescheduled.
 Mon Jan  4 14:35:00 BEIST 2016
! cron: 0481-087 The c queue maximum run limit has been reached.
 Mon Jan  4 14:35:00 BEIST 2016
! 0481-095 The cron job is being rescheduled.
 Mon Jan  4 14:35:00 BEIST 2016
! cron: 0481-087 The c queue maximum run limit has been reached.
 Mon Jan  4 14:35:00 BEIST 2016
! 0481-095 The cron job is being rescheduled.
 Mon Jan  4 14:35:00 BEIST 2016
! cron: 0481-087 The c queue maximum run limit has been reached.
 Mon Jan  4 14:35:00 BEIST 2016
! 0481-095 The cron job is being rescheduled.
 Mon Jan  4 14:35:00 BEIST 2016
! cron: 0481-087 The c queue maximum run limit has been reached.
 Mon Jan  4 14:35:00 BEIST 2016
! 0481-095 The cron job is being rescheduled.
 Mon Jan  4 14:35:00 BEIST 2016
! cron: 0481-087 The c queue maximum run limit has been reached.
 Mon Jan  4 14:35:00 BEIST 2016
! 0481-095 The cron job is being rescheduled.
 Mon Jan  4 14:35:00 BEIST 2016
! cron: 0481-087 The c queue maximum run limit has been reached.
 Mon Jan  4 14:35:00 BEIST 2016
! 0481-095 The cron job is being rescheduled.
 Mon Jan  4 14:35:00 BEIST 2016
! cron: 0481-087 The c queue maximum run limit has been reached.
 Mon Jan  4 14:35:00 BEIST 2016
! 0481-095 The cron job is being rescheduled.
 Mon Jan  4 14:35:00 BEIST 2016
! cron: 0481-087 The c queue maximum run limit has been reached.
 Mon Jan  4 14:35:00 BEIST 2016
! 0481-095 The cron job is being rescheduled.
 Mon Jan  4 14:35:00 BEIST 2016
! cron: 0481-087 The c queue maximum run limit has been reached.
 Mon Jan  4 14:35:00 BEIST 2016
! 0481-095 The cron job is being rescheduled.
 Mon Jan  4 14:35:00 BEIST 2016


问题原因:
crontab 没有定时执行是因为“! cron: 0481-087 The c queue maximum run limit has been reached.”。
修改/var/adm/cron/queuedefs 文件。在里面加上这样一句:"c.200j20n60w",然后kill PID,其中PID为cron进程号,新的cron设置就会生效。
Maximum number of jobs in the queue by default was 50. The errorc messages 0481-087, 0481-095 usually appears when this max. number
is reached. So you can increase the maximum number of jobs in /var/adm/cron/queuedefs , vi the queuedefs file and change
the b to c and the 50 to 200. by including this entry"c.200j20n60w" in the file. After making the changes to the file, 
killcron and it will respawn again with the new settings.
解决方法:
#
#
# here is an example of a low prority (nice 20), 50 entry batch queue
# b.50j20n60w
  c.600j10n120w
在/var/adm/cron/queuedefs/queuedefs加以C队列为1000就可以了。
ps -ef|grep cron
kill -9 con服务的进程号
cron的服务会自动重启,问题解决。


清理cron log文件(400M).

<think>我们参考了多个引用,特别是引用[1]提到了使用apscheduler定时调度框架,引用[2][3][4]提到了在Windows和Linux系统下设置定时任务的方法。 用户的需求是:用Python编写定时任务来自动创建文件并执行相关操作。 我们可以提供两种主要方法: 方法一:使用Python的定时任务库(如apscheduler)在程序中实现定时任务(跨平台) 方法二:使用操作系统定时任务机制(如Windows的任务计划程序或Linux的cron)来定时执行Python脚本 下面分别介绍这两种方法,并提供代码示例。 方法一:使用apscheduler库(纯Python实现,跨平台) 步骤: 1. 安装apscheduler:`pip install apscheduler` 2. 编写一个创建文件并执行操作的函数 3. 使用apscheduler设置定时任务 示例代码: ```python from apscheduler.schedulers.blocking import BlockingScheduler import datetime import os def create_file_job(): # 创建文件并写入内容 file_name = f"auto_created_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.txt" content = f"文件创建时间: {datetime.datetime.now()}\n这是自动创建的文件内容。" # 可以指定目录,确保目录存在 target_dir = "auto_files" os.makedirs(target_dir, exist_ok=True) file_path = os.path.join(target_dir, file_name) with open(file_path, 'w', encoding='utf-8') as f: f.write(content) print(f"已创建文件: {file_path}") if __name__ == '__main__': # 创建调度器 scheduler = BlockingScheduler() # 添加定时任务,这里使用cron表达式,表示每天10:30执行 scheduler.add_job(create_file_job, 'cron', hour=10, minute=30) # 也可以使用间隔触发,例如每10秒执行一次(测试用) # scheduler.add_job(create_file_job, 'interval', seconds=10) print("定时任务已启动,按Ctrl+C退出...") try: scheduler.start() except (KeyboardInterrupt, SystemExit): pass ``` 方法二:使用操作系统定时任务 对于Windows系统(参考引用[2][4]): 1. 编写一个Python脚本(如create_file.py),包含创建文件的代码 2. 打开“任务计划程序” 3. 创建基本任务,设置触发器(每天、特定时间等) 4. 操作选择“启动程序”,并填写Python解释器的完整路径和脚本的完整路径 - 程序或脚本:填写Python解释器的路径(如C:\Python39\python.exe) - 添加参数:填写脚本的完整路径(如D:\scripts\create_file.py) 注意:在Windows任务计划中执行时,由于工作目录可能不同,建议在脚本中使用绝对路径或显式设置工作目录。 对于Linux系统(参考引用[3]): 1. 编写Python脚本 2. 使用crontab设置定时任务 - 编辑crontab:`crontab -e` - 添加一行,例如:`30 10 * * * /usr/bin/python3 /path/to/your/script.py >> /path/to/log.log 2>&1` - 注意:指定Python解释器的绝对路径(通过`which python3`查看)和脚本的绝对路径 两种方法比较: - apscheduler:灵活,可随程序启动,适合作为程序的一部分,但需要程序一直运行 - 系统任务:不依赖程序运行,系统级调度,但需要配置系统任务 根据需求选择合适的方法。 最后,注意在定时任务中处理路径问题,建议使用绝对路径,或者使用os.path.dirname(__file__)来获取脚本所在目录,避免因工作目录不同导致的问题。 示例:在脚本中处理路径问题 ```python import os import datetime # 获取当前脚本所在目录 base_dir = os.path.dirname(os.path.abspath(__file__)) target_dir = os.path.join(base_dir, "auto_files") os.makedirs(target_dir, exist_ok=True) file_name = f"file_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.txt" file_path = os.path.join(target_dir, file_name) with open(file_path, 'w') as f: f.write("内容") ``` 相关问题: 1. 如何确保定时任务在服务器重启后仍然生效? 2. 如何记录定时任务的执行日志? 3. 在Windows任务计划程序中如何设置每分钟执行一次? 4. 如何避免同时运行多个相同的定时任务实例?</think>### 如何用 Python 编写定时任务自动创建文件 以下是两种主流方法实现定时文件创建任务,结合引用内容的关键知识点: --- #### 方法一:使用 Python 调度库(推荐跨平台方案) 参考引用[1]的 `apscheduler` 框架,适合纯 Python 环境: ```python from apscheduler.schedulers.blocking import BlockingScheduler from datetime import datetime import os def create_file_task(): """定时执行的文件创建任务""" # 生成带时间戳的文件名 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"auto_file_{timestamp}.txt" # 文件内容(可自定义) content = f"自动创建于 {datetime.now()}\n任务ID: {os.urandom(4).hex()}" # 创建并写入文件 with open(filename, 'w', encoding='utf-8') as f: f.write(content) print(f"✅ 已创建文件: {filename}") if __name__ == '__main__': scheduler = BlockingScheduler() # 添加定时任务(示例:每分钟执行一次) scheduler.add_job(create_file_task, 'interval', minutes=1) # 添加Cron式任务(示例:每天9:30执行) # scheduler.add_job(create_file_task, 'cron', hour=9, minute=30) print("⏰ 定时任务已启动 (Ctrl+C退出)...") try: scheduler.start() except KeyboardInterrupt: scheduler.shutdown() ``` **关键配置说明**: 1. **触发类型**: - `interval`:固定间隔执行(如每5分钟) - `cron`:Unix cron表达式(如 `hour=9, minute=30`) 2. **路径处理**(参考引用[2]): ```python # 显式指定工作目录(避免任务计划程序路径问题) target_dir = os.path.join(os.path.dirname(__file__), "output_files") os.makedirs(target_dir, exist_ok=True) filename = os.path.join(target_dir, filename) ``` 3. **日志记录**(参考引用[3]): ```python scheduler.add_job(create_file_task, 'cron', hour=9, minute=30, misfire_grace_time=300) ``` --- #### 方法二:操作系统定时任务 ##### Windows 系统(参考引用[4]) 1. 创建脚本 `file_creator.py`: ```python import os from datetime import datetime # 显式设置工作目录(解决引用[2]的路径问题) if __name__ == "__main__": base_dir = r"D:\AutoFiles" # 修改为实际路径 os.makedirs(base_dir, exist_ok=True) os.chdir(base_dir) # 关键!避免使用系统默认路径 filename = f"file_{datetime.now().strftime('%H%M')}.txt" with open(filename, 'w') as f: f.write("Windows任务计划创建的文件") ``` 2. 通过任务计划程序配置: - 触发操作:`程序或脚本` = `python.exe` 完整路径 - 参数 = 脚本完整路径(如 `D:\scripts\file_creator.py`) - 起始位置 = 脚本所在目录(如 `D:\scripts`) ##### Linux 系统(参考引用[3]) ```bash # 编辑crontab crontab -e # 添加行(每天8:15执行,记录日志) 15 8 * * * /usr/bin/python3 /home/user/auto_files.py >> /var/log/file_creator.log 2>&1 ``` --- ### 关键问题解决方案 1. **路径错误问题**(引用[2]): - 在脚本开头使用 `os.chdir(os.path.dirname(os.path.abspath(__file__)))` - 或绝对路径操作文件 2. **环境依赖问题**: ```python # 在脚本顶部指定解释器路径(Linux) #!/usr/bin/env python3 ``` 3. **错误处理增强**: ```python try: with open(filename, 'w') as f: f.write(content) except PermissionError: print("❌ 权限错误:尝试以管理员身份运行") except Exception as e: print(f"❌ 创建失败: {str(e)}") ``` --- ### 应用场景示例 ```python # 自动生成日报(每天17:00创建) def daily_report(): report_name = f"日报_{datetime.now().strftime('%Y-%m-%d')}.txt" content = get_daily_data() # 自定义数据获取函数 with open(report_name, 'w', encoding='utf-8') as f: f.write(content) # 配置APScheduler scheduler.add_job(daily_report, 'cron', hour=17, minute=0) ``` > 提示:生产环境建议添加任务互斥锁,防止重复执行[^1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值