【问题标题】:How to start over the count on the year change?如何重新开始计算年份变化?
【发布时间】:2022-01-23 21:09:23
【问题描述】:

我有一个用 java 编写的简单 android 应用程序。该应用程序是一个简单的计数应用程序,我可以在其中计算不同种类的鱼。为此,我实现了 SQLite RoomDB。我的表包含“ID”、“f_type”、“count”、“time”,例如01,“砂光机”,2,“2021 年 12 月 22 日下午 5:23:27”。从每条书面记录中,我根据鱼类类型计算了总数,例如

@Query("SELECT SUM(count)FROM catch_table WHERE f_type = 'sander' ")
    LiveData<String> getSanderTotalCount();

所有这些都按方面进行。但是,我想在年份更改时开始或将我的总计数重置为零。这样做的最佳做法是什么? 谢谢。

【问题讨论】:

  • 我个人会按年份进行搜索,这可以作为参数传递给 SQL 查询 - 类似于 getSanderTotalCount(String date) 并确保日期格式正确:D

标签: java android count


【解决方案1】:

我会使用ScheduledExecutorService 接口:

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.Executors;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.Duration;
import java.time.Year;


public class Main {
        
    public static void main(String[] args) {
        Scheduler scheduler = new Scheduler();
        scheduler.init();
    }
}

class Scheduler {
           
    public void init(){
        
        // specify interval (scheduled time - current time)        
        LocalDateTime current = LocalDateTime.now();           
        int year = Year.now().plusYears(1).getValue(); // increment current year to next year
        LocalDateTime schedule = LocalDateTime.of(year, Month.JANUARY, 1, 0, 1); // year, month, day, hour, minute
        
        // calculate duration
        Duration duration = Duration.between(current, schedule);
        long delay = Math.abs(duration.toMillis()); //or some other TimeUnit

        // reserve thread and schedule runnable task
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        ScheduledFuture<?> taskHandle = executor.schedule(() -> {
            
             // run your code here

            init(); // reinitialize for next schedule
        }, delay, TimeUnit.MILLISECONDS);
    }
}

some examples

【讨论】:

    猜你喜欢
    • 2010-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    相关资源
    最近更新 更多