Spring配置使用quartz
public interface SchedulerTask {
public void testMethod();
}
public class SchedulerTaskImpl implements SchedulerTask {
public void testMethod(){
System.out.println("helloworld"+new Date().toLocaleString());
}
}
<bean id="testService" class="com.downjoy.app.smtpfbackend.common.service.SchedulerTaskImpl">
</bean>
<!-- 注册具体的定时任务到applicationContext -->
<bean id="testJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!-- 任务具体对象 -->
<property name="targetObject" ref="testService"/>
<!-- 具体的方法 -->
<property name="targetMethod" value="testMethod"/>
</bean>
<!-- 配置触发器 ,为定时任务设置执行时间等属性 -->
<bean id="testJobCronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="testJob"/>
<!-- 每分钟触发一次 -->
<property name="cronExpression" value="0 */1 * * * ?"/>
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<!-- 添加触发器 -->
<property name="triggers">
<list>
<ref local="testJobCronTrigger"/>
</list>
</property>
</bean>
纯java代码使用quartz
/**
*
*/
package test;
import java.util.Date;
import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
class SchedulerManager{
public void start() throws SchedulerException
{
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
JobDetail jobDetail = new JobDetail("jobDetail", "jobDetailGroup", MyTimeTask.class);
CronTrigger cronTrigger = new CronTrigger("cronTrigger", "triggerGroup");
try {
CronExpression cexp = new CronExpression("1 * * * * ?");
cronTrigger.setCronExpression(cexp);
} catch (Exception e) {
e.printStackTrace();
}
scheduler.scheduleJob(jobDetail, cronTrigger);
scheduler.start();
}
}
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
try {
new SchedulerManager().start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class MyTimeTask implements Job{
public void execute(JobExecutionContext context) throws JobExecutionException{
System.out.println("helloWorld"+new Date().toLocaleString());
}
}
参考:
http://www.tuicool.com/articles/MBnYjmY