spring boot中简单定时任务

目录

1.使用方法

(1)启动类中开启定时任务

(2)创建定时任务,并设定定时任务的执行时间


1.使用方法

(1)启动类中开启定时任务

package com.example.demo;

import com.example.demo.domain.Student;
import com.example.demo.service.IBmsBillMemoService;
import com.example.demo.service.impl.BmsBillMemoServiceImpl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
//开启定时任务功能
@EnableScheduling
@EnableConfigurationProperties(Student.class)

public class DemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(DemoApplication.class, args);
        Object bean = ctx.getBean("bmsBillMemoServiceImpl");
        System.out.println(bean);
        IBmsBillMemoService bean1 = ctx.getBean(IBmsBillMemoService.class);
        System.out.println(bean1);
        BmsBillMemoServiceImpl bean2 = ctx.getBean("bmsBillMemoServiceImpl", BmsBillMemoServiceImpl.class);
        System.out.println(bean2);
    }

}

(2)创建定时任务,并设定定时任务的执行时间

package com.example.demo.quartz;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author linaibo
 * @version 1.0
 * Create by 2022/12/3 14:22
 */
@Component
public class Task {
    @Scheduled(cron = "0/1 * * * * ?")
    public void print(){
        System.out.println("开始执行");
    }
}

2.总结

在实际的项目开发中,除了使用上面的这种方式,常见的还有xxljob等

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值