Java实现定时任务

 Timer

jdk自带的api ,timer是一种定时器工具 用来是是心啊定时任务,可以用来执行一次或定期执行多次

package com.YJM.love.com.YJM.test;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author77918
 * @namelove_take_out
 * @date20232023/6/151:22
 */
public class Task1 {
    public static void main(String[] args) {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:MM:ss.SSS");
                String datestr= simpleDateFormat.format(new Date());
                System.out.println("定时任务"+datestr);

            }
        };
        //计时器
        Timer timer = new Timer();
        //添加执行任务 延迟1s执行,每3s执行一次
        timer.schedule(timerTask,1000,3000);

    }
}

二、Thread 线程等待

创建一个thread,while循环,sleep方法达到定时任务的效果

匿名内部类实现runnable接口 

package com.YJM.love.com.YJM.test;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author77918
 * @namelove_take_out
 * @date20232023/6/1521:17
 */
public class TreadTask {
    public static void main(String[] args) {

        final  long  timeInteval=1000;

        Thread thread= new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){

                    SimpleDateFormat simpleDateFormat= new SimpleDateFormat("HH:mm:ss.SSS");
                    String dateStr=simpleDateFormat.format(new Date());
                    System.out.println("线程等待实现任务"+ dateStr);

                    try {
                        Thread.sleep(timeInteval);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
          thread.start();
    }
}

2d8de6d2be874da98caabae76db4389e.png

package com.YJM.love.com.YJM.test;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author77918
 * @namelove_take_out
 * @date20232023/6/1521:25
 */
public class ThreadTask1 {
    public static void main(String[] args) {
        Myrunnable myrunnable = new Myrunnable();
        Thread t = new Thread(myrunnable);
        t.start();

    }


}


class  Myrunnable implements  Runnable{

    final  long timeInterval=1000;
    @Override
    public void run() {
        while (true){
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("HH:mm:ss.SSS");
            String datesttr=simpleDateFormat.format(new Date());
            System.out.println("线程等待实现任务1"+ datesttr);


            try {
                Thread.sleep(timeInterval);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}

 d310ef07b9d645ce852c1ee2102faf27.png

三 spring boot实现

p1简单实现

1.开启定时任务注解 

spring脚手架创建的项目

bb793fa11235408d9a3ac1ee45d6ae3c.png

2.设置执行时间

package com.yjm.javalearning.practiceschedule;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.DateFormat;
import java.util.Date;

@SpringBootApplication
@EnableScheduling
public class PracticeScheduleApplication {

    public static void main(String[] args) {
        SpringApplication.run(PracticeScheduleApplication.class, args);
    }
    /*
    * 半小时提醒一次
    * 
    * 
    * */
    
    @Scheduled(fixedRate = 30*60*1000)
    public  void playSth(){

        System.out.println("发送微信提醒博文多喝热水"+ DateFormat.getTimeInstance().format(new Date()));
        
    }
    
    /*
    * 4小时提醒一次
    *
    * */
    @Scheduled(fixedRate = 4*60*60*1000)
    public  void playSth2(){
        System.out.println("发送微信提醒博文多吃饭"+DateFormat.getTimeInstance().format(new Date()));
        
    }
    
    
}

p2 cron

cron在线表达式生成器可以帮助生成定时任务会提醒的时间

可以设置在什么时间段提醒 并且设置提醒间隔

package com.yjm.javalearning.practiceschedule;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.DateFormat;
import java.util.Date;

@SpringBootApplication
@EnableScheduling
public class PracticeScheduleApplication {

    public static void main(String[] args) {
        SpringApplication.run(PracticeScheduleApplication.class, args);
    }
    /*
    * 半小时提醒一次
    *只在白天提醒
    *
    * */
    @Scheduled(cron = "0 0/30 9-22 * * ?")
   // @Scheduled(fixedRate = 30*60*1000)
    public  void playSth(){

        System.out.println("发送微信提醒博文多喝热水"+ DateFormat.getTimeInstance().format(new Date()));

    }

    /*
    * 4小时提醒一次
    *只在白天提醒
    * */
    //@Scheduled(fixedRate = 4*60*60*1000)
    @Scheduled(cron = "0 0 9-22/4 * * ?")
    public  void playSth2(){
        System.out.println("发送微信提醒博文多吃饭"+DateFormat.getTimeInstance().format(new Date()));

    }


}

d2ff716c6a8c4f2993c3f8b437f9c0c8.png

a927b42d70a94b86850f048e0d88b73a.png

1c7aac94b5d84a92a0d92d2072e92766.png

异步多线程实现

默认是单线程的定时任务  如果任务执行时间较长 就会将后续定时任务拖延  导致任务丢失

1.开启异步注解

 

2.设置异步执行

package com.yjm.javalearning.practiceschedule;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.DateFormat;
import java.util.Date;

@SpringBootApplication
@EnableScheduling
@EnableAsync
public class PracticeScheduleApplication {

    public static void main(String[] args) {
        SpringApplication.run(PracticeScheduleApplication.class, args);
    }
    /*
    * 半小时提醒一次
    *只在白天提醒
    *线程异步
    * */
    @Async
   // @Scheduled(cron = "0 0/30 9-22 * * ?")
    @Scheduled(fixedRate = 1*60*1000)
    public  void playSth(){

        System.out.println("线程"+Thread.currentThread().getName());
        System.out.println("发送微信提醒博文多喝热水"+ DateFormat.getTimeInstance().format(new Date()));

    }

    /*
    * 4小时提醒一次
    *只在白天提醒
    * */
    @Scheduled(fixedRate =1*60*1000)
    @Async
   // @Scheduled(cron = "0 0 9-22/4 * * ?")
    public  void playSth2(){
        System.out.println("线程"+Thread.currentThread().getName());
        System.out.println("发送微信提醒博文多吃饭"+DateFormat.getTimeInstance().format(new Date()));

    }


}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值