几种定时任务实现方式

我所了解的定时任务有以下几种:

使用线程/线程池创建定时任务
使用 Quartz 框架实现定时任务
spring中可以使用 @Scheduled 注解实现定时任务

使用线程/线程池创建定时任务

package com.example.ScheduledTask;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
* Description: 线程定时任务  间隔时间执行
* date:  <br/>
* @author: kk <br/>
* @since JDK 1.8
*/

public class Scheduled01 {
    public static void main(String[] args) {

        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {

                        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        System.out.println( sdf.format(new Date()));
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }


            }
        };
        //方式一:线程休眠一定时间执行
        //Thread thread=new Thread(runnable);
        //thread.start();


        //方式二:线程池间隔时间执行
        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

        //第二个参数:首次延迟时间   第三个参数:间隔时间   第四个参数:单位 秒,分,时,天
        scheduledExecutorService.scheduleAtFixedRate(runnable,10,1, TimeUnit.SECONDS);


    }





}

使用 Quartz 框架实现定时任务

package com.example.ScheduledTask;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;

public class Scheduled03 {

    public static void main(String[] args) throws SchedulerException {
        //1.创建Scheduler的工厂
        SchedulerFactory sf = new StdSchedulerFactory();
        //2.从工厂中获取调度器实例
        Scheduler scheduler = sf.getScheduler();
        //3.创建JobDetail,

        JobDetail jb = JobBuilder.newJob(MySelfJob.class)
                //job的描述
                .withDescription("继承job重写方法")
                //job 的name和group
                .withIdentity("myselfJob", "myselfJobGroup")
                .build();

        //任务运行的时间,SimpleSchedle类型触发器有效,3秒后启动任务
        long time = System.currentTimeMillis() + 3 * 1000L;
        Date statTime = new Date(time);
        //4.创建Trigger
        //使用SimpleScheduleBuilder或者CronScheduleBuilder
        Trigger t = TriggerBuilder.newTrigger()
                .withDescription("")
                .withIdentity("myselfJobTrigger", "myselfJobTriggerGroup")
                //.withSchedule(SimpleScheduleBuilder.simpleSchedule())
                //默认当前时间启动
                .startAt(statTime)
                //10秒执行一次,Quartz表达式,支持各种牛逼表达式
                .withSchedule(CronScheduleBuilder.cronSchedule("0/10 * * * * ?"))
                .build();
        //5.注册任务和定时器
        scheduler.scheduleJob(jb, t);
        //6.启动 调度器
        scheduler.start();
    }


}

package com.example.ScheduledTask;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.text.SimpleDateFormat;

/**
 * 继承Quartz框架中的Job,并重写execute方法
 */
public class MySelfJob implements Job{

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("当前时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
    }

}

spring中可以使用 @Scheduled 注解实现定时任务

package com.example.ScheduledTask;

import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.SimpleDateFormat;

/**
 @EnableScheduling 开启对定时任务的支持
*/

@SpringBootApplication  //主程序启动类
@EnableScheduling       //开启对定时任务的支持
@Configuration // 这里使用@Component也行
public class Scheduled02 {

    // 5s执行一次   5min   20点执行
    @Scheduled(fixedRate = 5* 1 * 1000)
    //@Scheduled(fixedRate = 5* 60 * 1000)
    //@Scheduled(cron="0 0 20 * * ? *")
    private void updateTask() {
        System.out.println("通过注解@Scheduled实现定时任务 定时任务开始执行-------------------");
        System.out.println("当前时间=="+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(System.currentTimeMillis()));
    }

    public static void main(String[] args) {
        SpringApplication.run(Scheduled02.class, args);
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 答:Java实现定时任务方式有三种:1.使用java.util.Timer类;2.使用java.util.concurrent.ScheduledThreadPoolExecutor类;3.使用Quartz框架。 ### 回答2: Java实现定时任务有以下几种方式: 1. Timer类:Java提供了Timer类来帮助实现定时任务。通过创建一个Timer实例和一个TimerTask实例,可以设定任务的执行时间和间隔时间,然后使用Timer的schedule()方法来启动任务。 2. ScheduledExecutorService接口:Java提供了ScheduledExecutorService接口来实现定时任务。该接口继承自ExecutorService接口,可以使用ThreadPoolExecutor来实现。通过调用schedule()方法,可以设定任务的执行时间和间隔时间,然后将任务提交给ScheduledExecutorService。 3. cron表达式:在Java中,还可以使用cron表达式来实现定时任务。cron表达式是一种用来设置时间的字符串格式,通过设置不同的字段,可以实现精确到秒的定时任务。可以使用Quartz框架等工具来解析和执行cron表达式。 4. Spring框架的@Scheduled注解:如果在Spring框架中开发应用,可以使用@Scheduled注解来实现定时任务。通过在方法上标记@Scheduled注解,并设置相应的时间表达式,可以让方法在指定的时间间隔内执行。 需要注意的是,以上方式都是基于Java定时任务实现,可以根据具体需求选择最合适的方式实现定时任务。 ### 回答3: 在Java中,我们可以使用以下几种方式实现定时任务。 1. Timer类:Java中的Timer类是一个简单的定时器工具,它可以通过创建Timer对象并调用其schedule()方法来设置定时任务。该方法可以指定一个任务(实现了TimerTask接口的类)和一个延迟时间,然后在延迟时间之后开始执行定时任务。 2. ScheduledExecutorService接口:Java中的ScheduledExecutorService接口是一个在指定的延迟时间之后或者以固定的时间间隔重复执行任务的调度器。可以使用Executors工厂类的newScheduledThreadPool()方法创建ScheduledExecutorService对象,并使用其schedule()方法来设置定时任务。 3. Quartz框架:Quartz是一个功能强大且灵活的开源定时任务调度框架。它提供了许多高级的调度功能,如任务的并发执行、动态调度、集群支持等。使用Quartz框架,我们可以通过配置定时任务的详细信息(如触发器、调度器等),然后让框架来管理和执行定时任务。 4. Spring的Task:Spring框架提供了一个简单的任务调度器,可以通过配置的方式实现定时任务。在Spring的配置文件中,我们可以使用<task:scheduler>和<task:scheduled>标签来定义定时任务的调度器和具体的定时任务方法。 综上所述,Java实现定时任务方式有多种选择。根据需求的复杂性和灵活性的要求,我们可以选择适合的方式实现定时任务
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值