您的位置:首页 > 编程语言 > Java开发

java--定时任务的实现方式

2017-03-10 09:34 627 查看
用java实现具体业务时,很多地方都要涉及到定时任务,比如说定时发送邮件、定时推送消息、定时抢购手机(这里我就像吐槽一下某米了)等。最近要用到这玩意儿,就研究了一下,大概有如下实现方式。

1,使用ScheduledThreadPoolExecutor实现

ScheduledThreadPoolExecutor是ThreadPoolExecutor的子类。

具体用法(每天0点执行new Runnable()进程):

ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
Calendar calender = Calendar.getInstance();
calender.set(Calendar.HOUR, 0);
calender.set(Calendar.MINUTE, 0);
calender.set(Calendar.SECOND, 0);
long delay = calender.getTimeInMillis() - System.currentTimeMillis();

executor.scheduleAtFixedRate(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub

}
}, delay, 1, TimeUnit.DAYS);
scheduleAtFixedRate方法的四个参数:

command
- the task to execute   要执行的任务
initialDelay
- the time to delay first execution  延迟一段时间执行第一次
period
- the period between successive executions  两次执行之间间隔时间
unit
- the time unit of the initialDelay and period parameters   时间单位

2,使用Cron表达式实现
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: