【问题标题】:Android: Call method at specific timestamp [closed]Android:在特定时间戳调用方法[关闭]
【发布时间】:2020-07-07 16:34:25
【问题描述】:

如何在 System.currentTimeMillis() 的基础上调用特定时间戳(以毫秒为单位)的方法?

【问题讨论】:

标签: java android time


【解决方案1】:

ScheduledExecutorService

保留一个scheduled executor service 对象。

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor() ;

计算等待时间。

Instant then = Instant.ofEpochMilli( 1_594_139_504_827L ) ;
Instant now = Instant.now() ; 
Duration d = Duration.between( now , then ) ;
if( d.isNegative() ) { … error … going back in time }

将您的任务定义为RunnableCallable。您可以使用lambda syntax,如此处所示,或使用常规语法。

Runnable runnable =
        ( ) -> {
            System.out.println( "Doing some task. " + Instant.now() );
        };

提交给执行者服务。指定任务、等待运行该任务的时间量以及unit of that quantity of time(毫秒、秒、小时等)。

ses.schedule( runnable , d.toSeconds() , TimeUnit.SECONDS ) ;

您的可运行文件在后台线程上运行。永远不要从后台线程访问用户界面。请参阅 Android 文档:Communicate with the UI thread

请务必在您的应用结束之前正常关闭您的执行程序服务。否则后备线程池可能会无限期地运行。

这已经在 Stack Overflow 上多次解决。搜索以了解更多信息。

【讨论】:

    【解决方案2】:

    我希望我的问题是正确的!

    你可以先从你的时间戳计算延迟:(假设yourGivenTimestamp是未来)

    long yourGivenTimestamp = 1594139504827;
    long delay = yourGivenTimestamp - System.currentTimeMillis();
    

    然后将其传递给Handler 实例中的postDelayed() 方法:

    new handler().postDelayed(() -> myFancyMethod(), delay); 
    

    那么你的myFancyMethod()会在delay时间过去后执行

    更新

    Android 已弃用 Hanlder() 构造函数(无参数)。

    请改用new Handler( Looper.getMainLooper() )new Handler( Looper.myLooper() )。更多info

    【讨论】:

      猜你喜欢
      • 2018-08-04
      • 1970-01-01
      • 2011-10-06
      • 1970-01-01
      • 1970-01-01
      • 2013-05-15
      • 2011-06-04
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多