任务调度活动

业务需求,当添加新活动时,设置结束日期,当过了结束日期时,自动将活动状态改为无效。

通过任务调度框架,根据活动结束时间,将活动状态改为无效。

首先引入依赖


    org.quartz-scheduler
    quartz
    2.3.0

实现Job接口,重写execute方法,书写业务需求(此处暂无业务需求)

public class ActivityServiceImpl implements ActivityService, Job, Runnable 

完整如下

@Override
public void saveActivity(Activity activity) {
    activityDao.saveActivity(activity);
    //开启活动倒计时(修改state值为0)
    //借助第三方的任务调度框架 quartz
    Thread th = new Thread(this); //让调度框架进入另一个线程
    th.start();
}

/**
* Job是Quartz中的一个接口,接口下只有execute方法,在这个方法中编写业务逻辑。
*/
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    String printTime = new SimpleDateFormat("yy-MM-dd HH-mm-ss").format(new Date());
    System.out.println("PrintWordsJob start at:" + printTime + ", prints: Hello Job-" + new Random().nextInt(100));
}

@Override
public void run() {
    try {
        SchedulerFactory factory = new StdSchedulerFactory();
        Scheduler scheduler = factory.getScheduler();
        Activity activity2 = activityDao.findEndTime();
        JobDetail jobDetail = JobBuilder.newJob(ActivityServiceImpl.class)
        .withIdentity("job1", "group1").build();
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "triggerGroup1").startNow()//立即生效
        .withSchedule(SimpleScheduleBuilder.simpleSchedule()
        /*.withIntervalInSeconds(1)//每隔1s执行一次
        .repeatForever()*/).build();//一直执行

//4、执行
scheduler.scheduleJob(jobDetail, trigger);
scheduler.start();

//睡眠 
TimeUnit.MILLISECONDS.sleep(activity2.getEndTime().getTime() - activity2.getStartTime().getTime()); //设置结束时间-开始时间的数值
        scheduler.shutdown();
        activityDao.updateState(activity2.getId()); //将state更新为0
    } catch (Exception e) {
        e.printStackTrace();
    }
}

你可能感兴趣的:(quartz)