Java专题十六:定时任务

2021-02-07 14:19

阅读:749

标签:lis   sch   依赖   hat   str   htm   read   map   rate   

Java专题十六:定时任务

目录
  • Java专题十六:定时任务
    • 16.1. java.lang.Thread类
    • 16.2. java.util.Timer类
    • 16.3. java.util.concurrent.ScheduledExecutorService类
    • 16.4. 第三方quartz包

注意测试这些类时应该在主线程总执行,即main方法中执行,如果单元测试使用junit测试不出效果

16.1. java.lang.Thread类

public class ThreadTest {
    public static void main(String[] args){    
        Runnable beeper = new Runnable() {   
            public void run() {               
                while (true){          
                    System.out.println("beep");    
                    try {                 
                        /* 执行周期为3s */             
                        Thread.sleep(3 * 1000);            
                    }catch(InterruptedException e){     
                        e.printStackTrace();                 
                    }              
                }         
            }     
        };      
        Thread thread = new Thread(beeper);      
        thread.start();  
    }
}


16.2. java.util.Timer类

import java.util.Timer;
import java.util.TimerTask;

public class TimerTest{
    public static void main(String[] args){     
        Timer timer = new Timer();    
       TimerTask timerTask = new TimerTask() {    
            @Override   
            public void run() {   
                System.out.println("beep");       
            }     
        };    
        /* 2s后开始执行,执行周期为3s */
        timer.scheduleAtFixedRate(timerTask, 2 *1000, 3 * 1000); 
    }
}

16.3. java.util.concurrent.ScheduledExecutorService类

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class ScheduledExecutorServiceTest{
    public static void main(String[] args){     
        ScheduledExecutorService scheduler =  Executors.newScheduledThreadPool(1);
        Runnable beeper = new Runnable() { 
            public void run() {     
                System.out.println("beep");   
            }
        };
        /* 2s后开始执行,执行周期为3s */
        scheduler.scheduleAtFixedRate(beeper, 2, 3, TimeUnit.SECONDS);
    }
}

16.4. 第三方quartz包

1.添加依赖包(gradle)

compile ‘org.quartz-scheduler:quartz:2.3.0‘
compile ‘org.slf4j:slf4j-log4j12:1.7.10‘

除了添加定时任务jar包,还需要添加slf4j 和 log4j整合用的日志文件,详情参考官网

2.新建工作类

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

public class BeepJob  implements Job {    
    public BeepJob(){ 
    }    
    @Override  
    public void execute(JobExecutionContext context) throws JobExecutionException {          
        JobDataMap dataMap = context.getJobDetail().getJobDataMap();   
        System.out.println(dataMap.get("msg"));     
        System.err.println("BeepJob Executed");  
    }
}

3.设置并启动定时器开始执行工作

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory
;import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ScheduleTest {   
    public static void main(String[] args){      
        SchedulerFactory sf = new StdSchedulerFactory();   
        Scheduler scheduler = null;    
        try {        
            scheduler = sf.getScheduler();     
            /* 使用JobDetail中的JobDataMap携带数据 */    
            Map dataMap = new HashMap(); 
            dataMap.put("msg", "beep");        
            JobDataMap jobDataMap = new JobDataMap(dataMap);       
            /* 定义JobDetail */        
            JobDetail job = JobBuilder.newJob(BeepJob.class)    
		            .withIdentity("beep-job", "beep")                 
		            .usingJobData(jobDataMap)                
		            .build();   
            /* 定义开始时间 */    
            Date date = new Date(System.currentTimeMillis() + 2 * 1000);    
            /* Define a Trigger that will fire "date", and  repeat forever, 2s后开始执行,执行周期为3s */           
            Trigger trigger = TriggerBuilder.newTrigger()            
		            .withIdentity("beep-trigger", "beep")       
		            .startAt(date)                   
		            .withSchedule(SimpleScheduleBuilder.simpleSchedule()            
                    .withIntervalInSeconds(3)                    
		            .repeatForever())                
		            .build();           
            /* Tell quartz to schedule the job using our trigger */      
            scheduler.scheduleJob(job, trigger);          
            scheduler.start();    
        }catch (SchedulerException e){        
            e.printStackTrace();    
        }   
    }
}

Java专题十六:定时任务

标签:lis   sch   依赖   hat   str   htm   read   map   rate   

原文地址:https://www.cnblogs.com/myibu/p/12775701.html


评论


亲,登录后才可以留言!