如何在特定日期自动触发事件以重置 java 中的计数?

How to trigger event on specific date automatically to reset count in java?

我正在尝试更新每次按钮点击的按钮点击次数。我正在使用 spring 引导和 angular 作为 frontend.I 设法以编程方式计算按钮点击次数并保存在数据库中。但是我需要在每个月的第一天将这些计数重置为零。 我该怎么做?

/** On what day of each month should the count be reset? 1..28 */
static final int DAY_OF_MONTH_TO_RESET_COUNT = 1;
/** In what time zone should above day-of-month be interpreted? */
static final ZoneId timeZone = ZoneId.of("Asia/Pontianak");

public static void resetIfDue() {
    // substitute reset_date from DB here
    LocalDate lastResetDate = LocalDate.of(2020, Month.SEPTEMBER, 24);

    LocalDate nextResetDate = lastResetDate.plusMonths(1)
                                .withDayOfMonth(DAY_OF_MONTH_TO_RESET_COUNT);
    LocalDate today = LocalDate.now(timeZone);
    // "not after today" means today or before today
    if (! nextResetDate.isAfter(today)) {
        System.out.println("Reset the count and update the reset_date in the database");
        updateClickCounts();

    }
}

这里我得到了这个函数,我必须在哪一天重置计数。它将调用包含更新查询的 updateClickCounts() 函数。但是我想触发事件以在每个月的第 1 天自动调用 resetIfDue()。我怎样才能做到这一点?我是事件触发器的新手,所以我不明白它是如何工作的。

你可以使用cron,这里很简单example

您可以使用 spring cron,如下所示:

/** On what day of each month should the count be reset? 1..28 */
static final int DAY_OF_MONTH_TO_RESET_COUNT = 1;
/** In what time zone should above day-of-month be interpreted? */
static final ZoneId timeZone = ZoneId.of("Asia/Pontianak");

@Scheduled(cron="0 0 0 1 1/1 *")
public static void resetIfDue() {
    // substitute reset_date from DB here
    LocalDate lastResetDate = LocalDate.of(2020, Month.SEPTEMBER, 24);

    LocalDate nextResetDate = lastResetDate.plusMonths(1)
                                .withDayOfMonth(DAY_OF_MONTH_TO_RESET_COUNT);
    LocalDate today = LocalDate.now(timeZone);
    // "not after today" means today or before today
    if (! nextResetDate.isAfter(today)) {
        System.out.println("Reset the count and update the reset_date in the database");
        updateClickCounts();

    }
}

在spring boot main中添加@EnableScheduling注解class。