Java专题十六:定时任务

Posted 黄先生的日志

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java专题十六:定时任务相关的知识,希望对你有一定的参考价值。

Java专题十六:定时任务


注意测试这些类时应该在主线程总执行,即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<String, Object> 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专题十六:定时任务的主要内容,如果未能解决你的问题,请参考以下文章

odoo10学习笔记十六:定时任务

odoo10学习笔记十六:定时任务

函数计算进行自动化运维专题

java代码启动一个定时任务

Java定时任务:利用java Timer类实现定时执行任务的功能

Java 如何实现这样的定时任务