调用WebService接口(四)

上一集节目地址:
调用WebService接口(三)

如果你的需求和我是类似的,基本上你就可以解决了。其中有几个问题:
1、有没有管杀不管埋的(只管更改定时任务的频率,不管启动,不管关停,只要应用启动,就以一定的频率进行执行任务)。
2、有没有把定时任务保存到数据库中的。
3、…

别问了,你想要的都会有。
一、管杀不管埋的豪放派。
1、在启动类上加上注解
@EnableScheduling

2、Task类,实现SchedulingConfigurer

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import up.tour.link.service.TestService;

import java.util.Date;

//@EnableScheduling
@Component
public class DynamicScheduleTaskSecond implements SchedulingConfigurer {

    @Autowired
    private TestService testService;

    @Value("${schedule.cron}")
    private String cron;

    public String getCron() {
        return cron;
    }

    public void setCron(String cron) {
        this.cron = cron;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                try {
                    testService.getTourResult();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                if ("".equals(cron) || cron == null) {
                    return null;
                }
                CronTrigger cronTrigger = new CronTrigger(cron);
                return cronTrigger.nextExecutionTime(triggerContext);
            }
        });
    }
}

3、cron表达式配到配置文件中

String cron = 0 */3 * * * ?

4、每次不需要重启应用,只要修改配置文件中的cron表达式就可以。

二、数据库这种的。

参考一下别人,洒家也没搞过,之后有机会搞,会补充过来。
参考文献,定时任务,点击收获惊喜!!!

猜你喜欢

转载自blog.csdn.net/weixin_44458365/article/details/106997719