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方法的四个参数:
2,使用Cron表达式实现
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表达式实现
相关文章推荐
- 七、java实现定时任务的三种方式
- java定时任务实现的几种方式
- java中实现定时任务的方式详解
- Quartz定时任务(纯java方式实现)
- Java实现定时任务的三种方式
- Java 实现定时任务的四种方式
- java实现定时任务几种方式
- Java 实现定时任务的四种方式
- java 定时任务的几种实现方式
- java定时任务实现的几种方式
- java作业调度、定时任务实践(三种实现方式)
- java定时任务的两种实现方式
- 两种方式实现java定时器,使用quartz定时器框架和java自带Timer定时器,编写定时任务
- Java实现定时任务的3种方式
- Java实现定时任务的三种方式
- 【Java】定时任务的几种实现方式
- JAVA定时任务实现的几种方式
- JAVA实现定时任务的几种方式
- Java 定时任务的几种实现方式
- java实现定时任务的三种方式