本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/49975443
最近在学习定时相关的技术。当前,几乎所有的互联网公司都会涉及定时相关的业务。比如网站首页的定时更新,内容的定时推送等等都会涉及。在找工作面试中,面试官也会问相关的问题。所以,在对定时学习和理解的基础上,简单地整理了一下学习笔记,下文主要以代码的方式展示。启动一个定时任务的流程大致为:创建Marven项目->在pom文件中引入依赖包->配置需要执行的任务和时间->启动定时器->解析配置文件->获取待处理的类和方法->启动定时任务->执行具体的任务->监听->到下一次时间到达时再次执行。详情见下方代码,希望本文对你有所帮助。
1、由于创建的是marven项目,所以需要引入包。对应的pom文件如下。
<span style="font-size:18px;"> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.1.5</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.apache.qpid</groupId> <artifactId>qpid-client</artifactId> <version>0.28</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jms</artifactId> <version>4.1.5.RELEASE</version> </dependency></span>
2、要创建定时任务,需要配置待执行的类、类中的方法、方法的执行周期。这里指定待执行的定时任务名称为searchJob,方法名称为search,定时器执行时间为10秒/次。注:配置文件中可以加入多个定时任务,自行配置。
timer.properties文件信息如下: searchJob:search:0/10 * * * * ?
3、定时任务的入口类如下所示。首先,加载配置文件,获取待执行的定时任务和时间;其次,启动定时器,然后解析配置文件,获取加载的类的和方法;最后,启动定时任务,当时间到达指定执行时,会执行相应的方法。
try { /* * 加载定时任务 */ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("file:d:/conf/time-quartz.xml"); /* * 启动定时器 */ SchedulerFactory schedulerFactory = new StdSchedulerFactory(); Scheduler scheduler = schedulerFactory.getScheduler(); scheduler.start(); /* * 启动定时任务 */ for (String task : tasks) { String[] parm = task.split(":"); String beanName = parm[0]; String methodName = parm[1]; String cron = parm[2]; JobDataMap jobDataMap = new JobDataMap(); jobDataMap.put("object", applicationContext.getBean(beanName)); jobDataMap.put("methodName", methodName); JobDetail jobDetail = JobBuilder.newJob(JobAdapter.class). withIdentity(beanName, methodName).usingJobData(jobDataMap).build(); Trigger trigger = TriggerBuilder.newTrigger(). withIdentity(beanName, methodName).withSchedule(CronScheduleBuilder.cronSchedule(cron)).build(); scheduler.scheduleJob(jobDetail, trigger); } } catch (Exception e) { log.error(e.getMessage(),e); } }
4、定时任务代理
import java.lang.reflect.Method; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; /** * 定时任务代理 */ public class JobAdapter implements Job { private Object object; private String methodName; public Object getObject() { return this.object; } public void setObject(Object object) { this.object = object; } public String getMethodName() { return this.methodName; } public void setMethodName(String methodName) { this.methodName = methodName; } @Override public void execute(JobExecutionContext context) throws JobExecutionException { try { Method method = this.object.getClass().getMethod(this.methodName, new Class[0]); method.invoke(this.object, new Object[0]); } catch (Exception e) { throw new JobExecutionException(e.getMessage(), e); } } }
5、定时任务
import javax.annotation.Resource; import org.springframework.stereotype.Component; import com.timer.modules.SearchService; @Component("searchJob") public class SearchJob { @Resource private SearchService searchService; public void search(){ searchService.getSearhData(); } }
6、定时任务的实现类
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Service; @Service public class SearchService extends BaseJobService{ public void getSearhData() { System.err.println("开始写入数据:"); try { String filePath = System.getProperty("user.dir") + "\\src\\main\\java\\com\\timer\\dto\\" + "searchDto.txt"; File f = new File(filePath); if(f.exists() && f.length() > 10){ f.delete(); f = new File(filePath); f.createNewFile(); } FileWriter fileWritter = new FileWriter(f.getCanonicalPath(), true); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); List<String> content = getContent("http://www.baidu.com"); bufferWritter.newLine(); bufferWritter.newLine(); for (String str : content) { bufferWritter.write(new String(str.getBytes("gb2312"),"UTF-8")); bufferWritter.newLine(); } bufferWritter.flush(); bufferWritter.close(); System.err.println(content.toArray().toString()); } catch (IOException e) { e.printStackTrace(); } System.err.println("写入数据完成"); } private List<String> getContent(String path) { List<String> result = new ArrayList<String>(); StringBuffer sb = new StringBuffer(); try { java.net.URL url = new java.net.URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); connection.connect(); InputStream inputStream = connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = in.readLine()) != null) { result.add(line); } in.close(); } catch (Exception e) { sb.append(e.toString()); System.err.println(e); System.err.println("Usage: java HttpClient <URL> [<filename>]"); } return result; } }