Linux定时任务实现每秒执行一次

1 简介

crontab定时任务最小周期为1分钟,如果脚本的调度周期需要小于1分钟,crontab就无法直接使用了,不过可以使用以下方法实现调度周期小于1分钟的情况。
date >> /root/result.txt为需要定时执行的命令(当然该语句可以换成其他脚本,如果需要的话),周期为1秒,分为两步实现:

1、循环中实现1分钟执行60次;
2、crontab定时任务每分钟执行一次test.sh脚本
1、2步骤配合使用,就实现了date >> /root/result.txt命令每秒执行一次的需求。

2 编写/root/test.sh脚本

该方法适用于调度周期能被60整除的情况

#!/bin/bash
step=1
for (( i = 0; i < 60; i = (i+step) )); do
date >> /root/result.txt
sleep $step
done

exit 0

3 配置定时任务

定时任务配置为每隔1分钟执行一次

// 编辑crontab
crontab -e
// 添加定时任务
* * * * * sh /root/test.sh

*/1 * * * * sh /root/test.sh

4 实现结果

通过以上步骤,即可实现date >> /root/result.txt命令每秒执行一次,测试结果如下:  


相关推荐

  • 生成图片

    from PIL import Image, ImageColor, ImageDraw, ImageFont, ImageFilterdef create_image_with_text(size, color, text, font_path, font_size, text_color, shadow_color, output_path): """ Create a new image of specified size and color with centered text that has a border and shadow. :param size: A tuple con

  • 获取指定目录下的所有图片信息

    1 获取指定目录下的所有图片信息// 获取指定目录下的所有图片信息 public function getImagesInfo($directory) { $images = []; // 创建递归目录迭代器 $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY ); // 遍历目录中的每个文件 foreach (

  • Thinkphp各版本的PHP要求

    ThinkPHP 8.0:运行环境要求PHP8.0+,兼容PHP8.3ThinkPHP 6.1:运行环境要求PHP7.2+,兼容PHP8.1ThinkPHP 6.0:运行环境要求PHP7.2+,兼容PHP8.1ThinkPHP 5.1:运行环境要求PHP5.6+,兼容PHP8.0ThinkPHP 5.0:运行环境要求PHP5.4+,兼容PHP7.3