---
title: "Linux下实现秒级定时任务的两种方案（crontab 每秒运行）"
author: "shootyou"
date: "2011-10-30T12:53:00Z"
tags: []
slug: "linux-crontab"
draft: false
lastmod: "2012-01-07T13:54:34Z"
id: 1337202
url: "https://shootyou.iteye.com/blog/1337202"
---

第一种方案，当然是写一个后台运行的脚本一直循环，然后每次循环sleep一段时间。

while true ;do

command

sleep XX //间隔秒数

done

第二种方案，使用crontab。

我们都知道crontab的粒度最小是到分钟，但是我们还是可以通过变通的方法做到隔多少秒运行一次。

以下方法将每20秒执行一次

crontab -e  
\* * * * * /bin/date  
\* * * * * sleep 20; /bin/date  
\* * * * * sleep 40; /bin/date

说明：需要将/bin/date更换成你的命令即可

这种做法去处理隔几十秒的定时任务还好，要是每1秒运行一次就得添加60条记录。。。如果每秒运行还是用方案一吧。