[亲测]springboot中如何手动运行定时任务(方法中包含调用其他接口)

本文介绍在SpringBoot应用中如何手动运行定时任务,特别是在任务中调用其他接口的情况。通过实现Scheduled接口并重写afterPropertiesSet()方法,确保项目启动后能自动执行signForJob()定时任务。

springboot中定时执行signForJob()方法,当启动项目加载完配置后执行afterPropertiesSet()方法
在这里插入图片描述

代码如下:

package cn.com.casmart.scheduling.job.orders;

import cn.com.casmart.common.domain.common.JResult;
import cn.com.casmart.common.domain.entity.member.Institutes;
import cn.com.casmart.scheduling.api.InstitutesApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import org.springframework.beans.factory.InitializingBean;

@Component
public class OrdersDeliveryJob implements InitializingBean {

    private static final Logger logger = LoggerFactory.getLogger(OrdersDeliveryJob.class);

    @Autowired
    InstitutesApi institutesApi;

    @Scheduled(cron = "0 10 2 * * ? ")
    public void signForJob() {
        try {
            JResult<List<Institutes>> jResult = institutesApi.getSelfInspection();
            List<Institutes> institutesList = jResult.getData();
        } catch (Exception e) {
            logger.error("***任务处理时出错", e);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        signForJob();
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值