第一种:
在spring-context文件中配置
<task:scheduler id="taskScheduler" pool-size="100" />
<task:scheduled-tasks scheduler="taskScheduler">
<!-- 每天0点0分0秒触发任务 -->
<task:scheduled ref="cameraService" method="screen" cron="00 00 00 * * ?"/>
<!-- ref为引入bean 需要在之前配置 method:方法 bean里的方法(需要调用的方法) cron:时间表达式 可参考linux时间表达式 -->
</task:scheduled-tasks>
cameraService 下的 screen 方法:
public void screen() {
System.out.println("");
}
第二种:
使用ScheduleExecutorService接口
接口scheduleAtFixedRate原型定义及参数说明:
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
long initialDelay,
long period,
TimeUnit unit);
command:执行线程
initialDelay:初始化延时
period:两次开始执行最小间隔时间
unit:计时单位
使用示例:
public void startScheduled(List<Camera> cameras) {
private ScheduledExecutorService executor = Executors.newScheduledThreadPool(100);
long oneDay = 24 * 60 * 60 * 1000;
long initDelay = getTimeMillis(time) - System.currentTimeMillis();
initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;
executor.scheduleAtFixedRate(
new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
//执行的方法
}
},
initDelay,
oneDay,
TimeUnit.MILLISECONDS
);
}
private long getTimeMillis(String time) {
try {
DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");
Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);
return curDate.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
ScheduleExecutorService参考博客:https://blog.csdn.net/tsyj810883979/article/details/8481621
注:TaskScheduler接口下的定时任务经试验定时不能生效,之后去了解一下
TaskScheduler接口方法定义:
TaskScheduler参考博客:https://www.cnblogs.com/ElEGenT/p/6392465.html