一枝梅比花娇 2017-12-04 07:10 采纳率: 100%
浏览 2085
已采纳

用户可自定义向自己发送消息的时间,自定义定时器问题

需求描述:有这么一个系统,用户可自定义向自己发送消息的时间,比如:用户1定义:在每天12点向我发送消息、用户2定义:每周一向我发送消息...用户n定义:每周三向我发送消息
怎么实现呢?
贴上目前实现方法:

 public class TestTimerController implements CommandLineRunner {

    @Autowired
    TimerTestRepository testRepository;

    @Override
    public void run(String... args) throws Exception {
        List<TimerTest> list = (List<TimerTest>) testRepository.findAll();

        for(TimerTest time : list){
            testtimer(time);
        }
    }

    public void testtimer(TimerTest test) {
        Timer t = new Timer();

        t.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                log.info(test.getMsg());
            }
        },test.getDelay(),test.getPeriod());
    }
    }


@Data
@Entity
public class TimerTest {

    @Id
    private String id;

    //多久调度一次
    private long period;

    //程序启动后多久开始调度
    private long delay;

    //输出数据
    private String msg;

}
  • 写回答

5条回答 默认 最新

  • airfling 2017-12-04 07:18
    关注

    spring 集成quartz就可以了,里面可以使用cron表达式,创建一个定时任务,定时触发就可以了

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?