Spring自带定时器任务:
code:
import org.springframework.beans.factory.annotation.Configurable; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date; @Component @Configurable @EnableScheduling public class ScheduledTasks{ @Scheduled(fixedRate = 1000 * 30) public void reportCurrentTime(){ System.out.println ("Scheduling Tasks Examples: The time is now " + dateFormat ().format (new Date())); } //每1分钟执行一次 @Scheduled(cron = "0/4 * * * * * ") public void reportCurrentByCron(){ System.out.println ("Scheduling Tasks Examples By Cron: The time is now " + dateFormat ().format (new Date ())); } private SimpleDateFormat dateFormat(){ return new SimpleDateFormat ("HH:mm:ss"); } }
Output:
Scheduling Tasks Examples By Cron: The time is now 12:02:48 Scheduling Tasks Examples By Cron: The time is now 12:02:52 Scheduling Tasks Examples: The time is now 12:02:54 Scheduling Tasks Examples By Cron: The time is now 12:02:56 Scheduling Tasks Examples By Cron: The time is now 12:03:00 Scheduling Tasks Examples By Cron: The time is now 12:03:04 Scheduling Tasks Examples By Cron: The time is now 12:03:08 Scheduling Tasks Examples By Cron: The time is now 12:03:12 Scheduling Tasks Examples By Cron: The time is now 12:03:16 Scheduling Tasks Examples By Cron: The time is now 12:03:20 Scheduling Tasks Examples By Cron: The time is now 12:03:24 Scheduling Tasks Examples: The time is now 12:03:24 Scheduling Tasks Examples By Cron: The time is now 12:03:28
Quartz:
使用quartz实现定时任务。
Quartz设计者做了一个设计选择来从调度分离开作业。Quartz中的触发器用来告诉调度程序作业什么时候触发。框架提供了一把触发器类型,但两个最常用的是SimpleTrigger和CronTrigger。
SimpleTrigger为需要简单打火调度而设计。典型地,如果你需要在给定的时间和重复次数或者两次打火之间等待的秒数打火一个作业,那么SimpleTrigger适合你。另一方面,如果你有许多复杂的作业调度,那么或许需要CronTrigger。
CronTrigger是基于Calendar-like调度的。当你需要在除星期六和星期天外的每天上午10点半执行作业时,那么应该使用CronTrigger。正如它的名字所暗示的那样,CronTrigger是基于Unix克隆表达式的。
http://blog.csdn.net/github_34889651/article/details/52586234
https://my.oschina.net/hhaijun/blog/698498
http://www.jianshu.com/p/67c760de79d5