java如何实现定时任务_java定时任务怎么实现?

1. 用Timer和TimerTask

分析: 在实现时,Timer类可以调度任务,TimerTask则是通过在run()方法里实现具体任务。

Timer实例可以调度多任务,它是线程安全的。

当Timer的构造器被调用时,它创建了一个线程,这个线程可以用来调度任务。

import java.util.Timer;

import java.util.TimerTask;

public class Task2 {

public static void main(String[] args) {

TimerTask task = new TimerTask() {

@Override

public void run() {

// task to run goes here

System.out.println("Hello !!!");

}

};

Timer timer = new Timer();

long delay = 0;

long intevalPeriod = 1 * 1000;

// schedules the task to be run in an interval

timer.scheduleAtFixedRate(task, delay,

intevalPeriod);

} // end of main

}

2,.使用 ScheduledExecutorService

它有以下好处:

1.相比于Timer的单线程,它是通过线程池的方式来执行任务的

2.可以很灵活的去设定第一次执行任务delay时间

3.提供了良好的约定,以便设定执行的时间间隔

import java.util.concurrent.Executors;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;

public class Task3 {

public static void main(String[] args) {

Runnable runnable = new Runnable() {

public void run() {

// task to run goes here

System.out.println("Hello !!");

}

};

ScheduledExecutorService service = Executors

.newSingleThreadScheduledExecutor();

service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.SECONDS);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值