需求描述:有这么一个系统,用户可自定义向自己发送消息的时间,比如:用户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;
}