1. 继承TimerTask类
```java
import java.util.Timer;
import java.util.TimerTask;
public class MyTimeTask extends TimerTask {
@Override
public void run() {
System.out.println("定时任务抱起来");
}
public static void main(String[] args) {
Timer timer = new Timer();
MyTimeTask myTimeTask = new MyTimeTask();
timer.schedule(myTimeTask,0,5000);
// 每隔5秒执行一次
}
}
2. 实现Runnable接口
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class MyScheduledTask implements Runnable{
@Override
public void run() {
System.out.println("牛马努力工作");
}
public static void main(String[] args) {
ScheduledExecutorService scheduledExecutorService= Executors.newScheduledThreadPool(1);
MyScheduledTask myScheduledTask = new MyScheduledTask();
//5秒执行一次
scheduledExecutorService.scheduleAtFixedRate(myScheduledTask,5,5, TimeUnit.SECONDS);
}
}
3. 使用注解
注意,一个方法上只能加上一个注解,要在启动类添加
@EnableScheduling // 启用定时任务调度功能 注解
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class MyNiuMa {
@Scheduled(fixedRate = 5000) // 每5秒执行一次
public void task1() {
System.out.println("牛马好好工作,每5秒执行一次");
}
@Scheduled(fixedDelay = 5000) // 上一次任务执行完毕后,延迟5秒再执行
public void task2() {
System.out.println("牛马好好工作,上一次任务执行完毕后,延迟5秒再执行");
}
@Scheduled(cron = "0 0 12 * * ?") // cron表达式,每天中午12点执行任务
public void task3() {
System.out.println("牛马好好工作,每天中午12点执行任务");
}
}
4还有一个Quartz
Quartz
java
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
public class MyJob implements Job {
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("Quartz Job is running");
}
public static void main(String[] args) throws SchedulerException {
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
JobDetail job = newJob(MyJob.class)
.withIdentity("job1", "group1")
.build();
// 每隔5秒执行一次
Trigger trigger = newTrigger()
.withIdentity("trigger1", "group1")
.startNow()
.withSchedule(simpleSchedule()
.withIntervalInSeconds(5)
.repeatForever())
.build();
scheduler.scheduleJob(job, trigger);
}
}