【问题标题】:How to manipulate a parameter in mySQL according to server time如何根据服务器时间操作mySQL中的参数
【发布时间】:2018-04-07 15:37:19
【问题描述】:
我已经用 Spring/hibernate/mySQL 构建了一个带有数据库的 RESTful 服务器。
我有一个银行储蓄账户表,其中包含 3 个储蓄余额列。
例如:
account_id | a_savings | b_savings | c_savings
1 | 100 | 200 | 300
我希望每天(或每月),每个储蓄账户都会根据服务器/当前时间自动为其价值增加 0.01%(或其他金额)。
我该怎么做?
【问题讨论】:
标签:
java
mysql
hibernate
spring-mvc
【解决方案1】:
编写一个暂停一段时间的方法,而不是调用一个暂停的方法
- 通过 SQL 加载字段的当前值
- 通过计算字段的值来增加字段的值,
value = value+(value*0.01) 然后使用 SQL 更新该值。
对于 java 中的暂停使用 TimeUnit.MINUTES.sleep(2); 的 java.util.concurrent.TimeUnit 这里 2 代表 2 Minutes 。您也可以使用 DAYS/HOURS TimeUnit.DAYS.sleep(1);
【解决方案2】:
通过调度任务解决了这个问题:
@Component
public class ScheduledTasks {
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Autowired
private SavingsAccountDao savingsAccountDao;
/* each day at 8 am */
@Scheduled(cron = "0 0 8 * * *")
public void increaseSavingsAccount() {
log.info("Savings Accounts Updated", dateFormat.format(new Date()));
/* get all savings accounts and increase balance according to the interest */
List<SavingsAccount> savingsAccountList = savingsAccountDao.findAll();
savingsAccountList.forEach((sa) -> {
/* 39% interest in 12 months */
sa.setASavingsBalance(sa.getASavingsBalance().multiply(new BigDecimal(1.0009)));
});
}
}