【发布时间】:2018-05-09 14:22:50
【问题描述】:
我有一个方法可以定期更新数据库中的记录。
@Service
public class MyService {
@Autowired
private MyRepository myRepository;
private Boolean flag = false;
@Transactional
public int method1(Args args) {
// do something
if (!flag) {
method2()
}
return x;
}
@Transactional
public int method2(Args args) {
polling = true;
Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
List<Records> records = myRepository.getRecords()
for (Record record : records ) {
// prints the Id of each record. Now, they are all have Id=1
System.out.println(record.getId());
// setting the record's Id to 5
record.setId(5);
// prints '5'
System.out.println(record.getId());
}
}
}, 10, 1000*60*4
}
}
Method1 调用 Method2。 Method2 每 4 分钟执行一次 run() 函数内的代码。 run() 中的代码无需调度即可正常工作(获取每条记录的 Id,打印它们,通过将 Id 设置为 5 来更新数据库)。 然而,现在,随着我使用 TimerTask,它仍然检索并打印 Id,据说将每条记录的 Id 设置为 5,甚至在 record.get(Id) 处打印出“5”,这让我相信数据库是成功的使用新 ID 更新。 当我实际检查我的数据库时,我发现 Ids 实际上没有更新到 5。原始 Ids 仍然存在。 我不确定为什么会发生这种情况,因为似乎 ID 正在更新。这与 TimerTask 创建新线程有关吗?
【问题讨论】:
-
您正在从 inside 方法中分离出
TimerTask,但您的任务方法本身并不是事务性的。请改用@Scheduled。 -
使用@Scheduled 并让它工作。谢谢!
标签: java spring spring-mvc scheduled-tasks timertask