java定时任务执行有很多种方法,这里介绍一下quartz配置使用。
一、准备需要的jar包:我自己使用的是quartz-1.6.0.jar ; commons-collections--3.2.jar ;commons-logging-1.0.4.jar,当然你下载的时候也可以下载最新版本的。
二、在web.xml中加入如下配置
<servlet>
<servlet-name>QuartzInitializer</servlet-name>
<servlet-class>org.quartz.ee.servlet.QuartzInitializerServlet</servlet-class>
<init-param>
<param-name>config-file</param-name>
<param-value>/quartz.properties</param-value>
</init-param>
<init-param>
<param-name>shutdown-on-unload</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
三、编写quartz.properties文件,配置内容如下,把这个文件放入根目录下即可
org.quartz.scheduler.instanceName = TestScheduler
org.quartz.scheduler.instanceId = one
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 2
org.quartz.threadPool.threadPriority = 4
org.quartz.plugin.triggHistory.class = org.quartz.plugins.history.LoggingTriggerHistoryPlugin
org.quartz.plugin.triggHistory.triggerFiredMessage = Trigger {1}.{0} fired job {6}.{5} at: {4, date, HH:mm:ss MM/dd/yyyy}
org.quartz.plugin.triggHistory.triggerCompleteMessage = Trigger {1}.{0} completed firing job {6}.{5} at {4, date, HH:mm:ss MM/dd/yyyy} with resulting trigger instruction code: {9}
org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.JobInitializationPlugin
#需要注意这里有些人可能配置完会报错,提示什么没有fileName这个属性,我当时是配置的是org.quartz.plugin.jobInitializer.fileNames=quartz_job.xml,结果启动项目就报错了,后来才改成org.quartz.plugin.jobInitializer.fileName,这个跟quartz.jar版本有关系,大家到时注意一下就行了
org.quartz.plugin.jobInitializer.fileName = quartz_job.xml
org.quartz.plugin.jobInitializer.overWriteExistingJobs = false
org.quartz.plugin.jobInitializer.failOnFileNotFound = true
org.quartz.plugin.shutdownhook.class = org.quartz.plugins.management.ShutdownHookPlugin
org.quartz.plugin.shutdownhook.cleanShutdown = true
四、编写quartz_job.xml,配置如下,放到根目录下既可
<?xml version="1.0" encoding="UTF-8"?>
<quartz>
<job>
<!--如果有多个定时任务就配置多个job-detail-->
<job-detail>
<name>pickBackJob</name>
<group>group1</group>
<job-class>com.landray.kmss.cultraview.supplier.job.PickBackJob</job-class><!--定时任务java类-->
</job-detail>
<trigger>
<cron>
<name>pickBackJob</name>
<group>group1</group>
<job-name>pickBackJob</job-name>
<job-group>group1</job-group>
<cron-expression>0 16 12 * * ?</cron-expression><!--定时任务时间配置-->
</cron>
</trigger>
</job>
</quartz>
五、编写定时任务java类
public class PickBackJob implements Job {//要实现Job接口,重写execute方法
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
// TODO Auto-generated method stub
//处理定时任务业务逻辑
}
}