本文参考至《Java7并发编程实战手册》
本文将会介绍Spring的@Schedule注解和Listen实现定时器注册的
延时执行任务的方法:
//涉及的类:ScheduleThreadPoolExecutor
public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit);
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit);
这里做个实例解释:
package ExecutorDelayTaskTest;
import java.util.Date;
import java.util.concurrent.Callable;
/**
* 任务类
* @author JM
* @2017-3-9
*/
public class Task implements Callable<String> {
private String name;
public Task(String name) {
super();
this.name = name;
}
@Override
public String call() throws Exception {
System.out.printf("%s:have started-----------.Time: %s\n", name, new Date());
return name + ":is end";
}
}
package ExecutorDelayTaskTest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 测试类
* @author JM
* @2017-3-9
*/
public class Main {
public static void main(String[] args) {
ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1);
List<Future<String>> resultList = new ArrayList<Future<String>>();
for (int i = 1; i <= 10; i++) {
Task task = new Task("task-" + i);
//三个参数分别代表:需要被执行的任务、执行该任务的延迟时间量(无单位量)、延迟时间的单位(毫秒、秒、天)
Future<String> result = executor.schedule(task, i, TimeUnit.SECONDS);
resultList.add(result);
}
for (int i = 0; i < resultList.size(); i++) {
try {
System.out.println(resultList.get(i).get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
executor.shutdown();
}
}
周期性执行任务的方法:
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);
代码案例:(启动下面将会一直执行下去,除非你关掉)
package ExecutorPeriodTaskTest;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
Task task = new Task("task-1");
System.out.printf("Main start at :%s\n",new Date());
executorService.scheduleWithFixedDelay(task, 4, 2, TimeUnit.SECONDS);
}
}
class Task implements Runnable {
private String name;
public Task() {
super();
}
public Task(String name) {
this.name = name;
}
@Override
public void run() {
System.out.printf("%s: have started,time is %s\n", this.name, new Date());
}
}
web项目中Spring注册定时任务
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpServletRequest;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.com.vsa.mine.model.Nordouniu;
@RequestMapping("/ashusuiahs")
@Controller
public class TestController extends BaseController<Long, Nordouniu>{
private static AtomicInteger s = new AtomicInteger(1);
//web项目通过可以通过@Scheduled(cron = "....")来注册执行定时周期任务
@Scheduled(cron = "0/1 * * * * ?")
public void add(){
s.addAndGet(1);
}
@RequestMapping("/studySkill")
@ResponseBody
public Object getS(HttpServletRequest request){
Map<String,Object> successMap = successMap();
successMap.put("s", s.get());
return successMap;
}
}
web项目可以使用Listener
定时执行的任务:
import java.util.concurrent.atomic.AtomicInteger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class TestTask implements Job {
private AtomicInteger i = new AtomicInteger(0);
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
i.addAndGet(1);
System.out.println(i.get());
}
}
自定义的Listener:
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import cn.web.controller.TestTask;
public class TestListener implements ServletContextListener{
public static Scheduler scheduler=null;
@Override
public void contextInitialized(ServletContextEvent sce) {
try {
if(scheduler==null){
scheduler=StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
JobDetail testJobDetail=new JobDetail("testJobDetail", "TimeTaskJob", TestTask.class);
CronTrigger testTrigger=new CronTrigger("testTrigger","TimeTaskTrigger","0/1 * * * * ?");
scheduler.scheduleJob(testJobDetail, testTrigger);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
web.xml的配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>cn.web.listener.TestListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
网友评论