業務需求,當添加新活動時,設置結束日期,當過告終束日期時,自動將活動狀態改成無效。框架
經過任務調度框架,根據活動結束時間,將活動狀態改成無效。dom
首先引入依賴ide
<dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency>
實現Job接口,重寫execute方法,書寫業務需求(此處暫無業務需求)ui
public class ActivityServiceImpl implements ActivityService, Job, Runnable
完整以下this
@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();//一直執行 //四、執行 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(); } }