package com.younike.common.quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.TimeUnit;


/**
 * Quartz定时任务demo
 * 2021-7-23 Another
 */
public class QuartzTaskDemo implements Job {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) 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));
    }

    public static void main(String[] args) throws SchedulerException, InterruptedException {
        // 1. 创建调度器工厂
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        // 2. 由调度器工厂创建调度器
        Scheduler scheduler = schedulerFactory.getScheduler();

        // 3. 创建 TaskDemo 实例（定时任务执行内容）
        JobDetail jobDetail = JobBuilder.newJob(QuartzTaskDemo.class)
                .withIdentity("job1", "group1").build();

        // 4. 创建触发器对象（Trigger实例），每隔1s执行一次
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "triggerGroup1")
                .startNow()//立即生效
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(1)//每隔1s执行一次
                        .repeatForever()).build();//一直执行

        // 5. 执行
        scheduler.scheduleJob(jobDetail, trigger);
        System.out.println("--------scheduler start ! ------------");
        scheduler.start();

        // 6. 结束
        TimeUnit.MINUTES.sleep(1);
        scheduler.shutdown();
        System.out.println("--------scheduler shutdown ! ------------");

    }

}
