美文网首页
2018-11-23

2018-11-23

作者: woshi开心 | 来源:发表于2018-11-23 14:45 被阅读0次

    Quartz

    Quartz:主要由以下几个组成Scheduler,job,JobDetail,Trigger,JobBuilder,TriggerBuilder。job:定义你想要被scheduler处理的逻辑,jobDetail,用于初始化job实例。trigger用于处理给定的job什么是很好开始执行。jobBuilder用于定义或者构建JobDetail实例,TriggerBuilder用于定义或者构建一个Trigger实例

    // define the job and tie it to our HelloJob class  
    JobDetail job = newJob(HelloJob.class)
          .withIdentity("myJob", "group1") // name "myJob", group "group1"
          .build();
    // Trigger the job to run now, and then every 40 seconds
      Trigger trigger = newTrigger()
          .withIdentity("myTrigger", "group1")
          .startNow()
          .withSchedule(simpleSchedule()
              .withIntervalInSeconds(40)
              .repeatForever())            
          .build();
    
      // Tell quartz to schedule the job using our trigger
      sched.scheduleJob(job, trigger);
    

    job 初始化

     import java.util.Date;
    import org.quartz.Job;
    import org.quartz.JobExecutionContext;
    import org.quartz.JobExecutionException;
    public class HelloJob implements Job {
    
        public HelloJob() {
        }
    
        public void execute(JobExecutionContext context)
          throws JobExecutionException
        {
          System.err.println("Hello!  HelloJob is executing.");
        }
      }
    

    当把job加载到scheduler时,jobDetail会被创建,jobDetail中存储一些job的状态信息

    • jobDataMap 用来存储一些数据对象,当job实例化执行时获取这些对象值
    JobDetail job = newJob(DumbJob.class)
          .withIdentity("myJob", "group1") // name "myJob", group "group1"
          .usingJobData("jobSays", "Hello World!")
          .usingJobData("myFloatValue", 3.141f)
          .build();
    public class DumbJob implements Job {
    
        public DumbJob() {
        }
    
        public void execute(JobExecutionContext context)
          throws JobExecutionException
        {
          JobKey key = context.getJobDetail().getKey();
    
          JobDataMap dataMap = context.getJobDetail().getJobDataMap();
    
          String jobSays = dataMap.getString("jobSays");
          float myFloatValue = dataMap.getFloat("myFloatValue");
    
          System.err.println("Instance " + key + " of DumbJob says: " + jobSays + ", and val is: " + myFloatValue);
        }
      }
    

    http://www.quartz-scheduler.org/documentation/quartz-2.2.x/tutorials/tutorial-lesson-09.html

    相关文章

      网友评论

          本文标题:2018-11-23

          本文链接:https://www.haomeiwen.com/subject/udfjqqtx.html