定时器java_java的几种定时器

1.@Scheduled注解

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

在spring配置中加入:

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

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

}2.quartz

quartz使用的是可配置的方式,将所有的定时器都配置再一个xml文件里面。步骤如下:1.创建一个spring的配置文件:spring-quartz.xml2.定义工作任务的job3.定义触发器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, longperiod)

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

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

第三个位多久运行一次,单位毫秒;new Timer().schedule(newTimerTask() {

@Overridepublic voidrun() {try{//do Something

} catch(Exception e) {

e.printStackTrace();

}

}

},0,5L * 60 * 1000);4.使用线程控制

使用线程来控制就更灵活一些,可以根据自己的需要判断什么时候运行,什么时候停止,这需要对java的线程有一定的了解。public classTaskTest {private static final ExecutorService pool = Executors.newFixedThreadPool(5);//线程池

public static final TaskTest me = newTaskTest();public final int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};public static voidmain(String[] args) {

me.start();

}private voidstart() {

pool.execute(newRunnable() {

@Overridepublic voidrun() {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();

}

}

}

});

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值