java的几种定时器

总结一下我使用过的4种类型的定时器:@Scheduled注解、quartz、new Timer().schedule、使用线程控制。


1.@Scheduled注解

@Scheduled注解是最简单的方式,只需要启用定时器,在方法上添加注解即可。

在spring配置中加入:


	

在要具体的方法上加入注解@Scheduled

@Scheduled(cron = "0 0 * * * ? ")
    public void myTask(){
           //定时任务......
}

2.quartz

           quartz使用的是可配置的方式,将所有的定时器都配置再一个xml文件里面。步骤如下:

1.创建一个spring的配置文件:spring-quartz.xml

2.定义工作任务的job

3.定义触发器Trigger并与job绑定

4.定义调度器,并将Trigger注册到scheduler


    
	
    
        
        
        
        
        
    
    
    
        
        
        
    

   

        
            
                 
            
        
    

最后记得将xml写入web.xml里!

    
      contextConfigLocation
      
				classpath:applicationContext.xml,
				classpath:log4j.xml,
                classpath:spring-quartz.xml
			
    

3.使用Timer

使用Timer的schedule,schedule有3个参数:

schedule(TimerTask task, long delay, long period)

第一个为定时任务,根据业务需要重写TimerTask的run方法即可;

第二个为延时启动,单位毫秒;

第三个位多久运行一次,单位毫秒;

new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                try {
                    //do Something
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },0,5L * 60 * 1000);

4.使用线程控制

   使用线程来控制就更灵活一些,可以根据自己的需要判断什么时候运行,什么时候停止,这需要对java的线程有一定的了解。

public class TaskTest {
    private static final ExecutorService pool = Executors.newFixedThreadPool(5);// 线程池
    public static final TaskTest me = new TaskTest();
    public final int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};

    public static void main(String[] args) {
        me.start();
    }

    private void start() {
        pool.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        for (int i = 0; i < arr.length; i++) {
                            if (1 == arr[i]) {
                                System.out.println("start!");
                                Thread.sleep(1*1000L);
                            }
                            if (6 == arr[i]) {
                                System.out.println("stop!");
                                Thread.sleep(5*1000L);
                            }
                            System.out.println(arr[i]);
                            if (9 == arr[i]) {
                                System.out.println("end!");
                                Thread.sleep(5*1000L);
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}

 

你可能感兴趣的:(java,util)