安排任务在特定时间每天运行

时间:2015-03-08 15:23:22

标签: java servlets scheduled-tasks quartz-scheduler

我正在尝试在每天上午8点和下午12点在我的Servlet / JSP应用程序中执行特定的工作。 Quartz库似乎是理想的,所以我尝试使用它。

我在下面的链接中使用了两个教程和示例。

http://www.mkyong.com/java/quartz-2-scheduler-tutorial/

http://www.javacodegeeks.com/2012/07/quartz-2-scheduler-example.html

以下是尝试

工作类

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class HelloJob implements Job
{
    public void execute(JobExecutionContext context)
    throws JobExecutionException {

        System.out.println("Hello Quartz!");    

    }

}

触发类

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class SimpleTriggerExample {
    public static void main(String[] args) throws Exception {



        JobDetail job = JobBuilder.newJob(HelloJob.class)
            .withIdentity("dummyJobName", "group1").build();



        // Trigger the job to run on the next round minute
        Trigger trigger = TriggerBuilder
            .newTrigger()
            .withIdentity("dummyTriggerName", "group1")
            .withSchedule(
                SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(5).repeatForever())
            .build();

        // schedule it
        Scheduler scheduler = new StdSchedulerFactory().getScheduler();
        scheduler.start();
        scheduler.scheduleJob(job, trigger);

    }
}

然而,两者都不能满足我的需要。它们不会在特定时间运行。如何在每天上午8点和下午12点使用Quarts执行作业?

2 个答案:

答案 0 :(得分:1)

尝试使用Cron创建计划:

    Trigger trigger = TriggerBuilder
            .newTrigger()
            .withIdentity("triggerName","triggerGroup")
           .withSchedule(CronScheduleBuilder.cronSchedule("0 0 12 * * ?")).build();

    Trigger trigger = TriggerBuilder
            .newTrigger()
            .withIdentity("triggerName","triggerGroup")
           .withSchedule(CronScheduleBuilder.cronSchedule("0 0 8 * * ?")).build();

答案 1 :(得分:0)

Trigger trigger = TriggerBuilder
            .newTrigger()
            .withIdentity("triggerName","triggerGroup")
           .withSchedule(CronScheduleBuilder.cronSchedule("0 30 12 * * ?")).build(); //schedules a job for 12:30am

    Trigger trigger = TriggerBuilder
            .newTrigger()
            .withIdentity("triggerName","triggerGroup")
           .withSchedule(CronScheduleBuilder.cronSchedule("0 0 14 * * ?")).build(); //schedules a job for 2pm

使用此网站获取有关日程安排的重要信息: http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html