使用Quartz框架构建一个定时任务的实例

1.引入Quartz框架所需jar包。

2.新建任务类---实现Job接口

 

package my.task;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class MyTask implements Job {
                                                      
    private static final Logger logger = Logger
            .getLogger(MyTask.class);  
    @Override
    public void execute(JobExecutionContext context)
            throws JobExecutionException {
        try {
            logger.info("Task started.");          
            // 写入你要做的定时任务
            System.out.println("my job!"+ new Date().toString());
            logger.info("Task finished.");         
        } catch (Exception e) {
            logger.error("execute Task error", e);
        }
    }
}

3. 主方法。

package my;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.repeatSecondlyForever;
import static org.quartz.TriggerBuilder.newTrigger;
import org.apache.log4j.Logger;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
public class Main {
    private static Logger logger = Logger.getLogger(Main.class);
    public static void main(String[] args) {
        logger.warn("started");
        try {
            org.quartz.Scheduler taskScheduler = StdSchedulerFactory
                    .getDefaultScheduler();
            taskScheduler.start();
                
                JobDetail myJob = newJob(MyTask.class)
                        .withIdentity("myJob").build();
                Trigger myTrigger = newTrigger()
                        .withIdentity("myJob").startNow()
                        .withSchedule(repeatSecondlyForever(60*60))
                        .build();
                taskScheduler.scheduleJob(myJob, myTrigger);
                    
                    
        } catch (Throwable t) {
            logger.error("Failed to schedule quartz tasks!", t);
        }
    }
}


你可能感兴趣的:(quartz,实例)