防止NSTimer在后台应用中触发延迟 [英] Prevent NSTimer firing delays in background app

查看:168
本文介绍了防止NSTimer在后台应用中触发延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个macOS应用程序(我们称其为显示应用程序")来显示时钟和其他数据,这些数据由同一计算机上的另一个应用程序(控制应用程序")通过TCP连接进行控制.我注意到,当显示应用空闲一段时间(> 60秒),然后安排一个NSTimer(间隔为.2秒)时,它会花费很长的时间才触发计时器第一次(在6到10秒之间,有时更长).这种情况通常发生在显示应用程序不在最前面时(因为控件应用程序在最前面).一旦计时器首次触发,它就会按预期工作(会有一些小的预期延迟).

I'm working on a macOS app (let's call it the "display app") that displays a clock and other data, which is controlled by another app (the "control app") on the same machine via a TCP connection. I have noticed that when the display app is idle for some time (> 60 sec.) and then schedules an NSTimer (with a .2 second interval), it takes a very long time before the timer fires for the first time (in the range of 6-10 seconds, sometimes longer.) That happens mostly when the display app is not frontmost (because the control app is.) Once the timer fired for the first time, it works as expected (with some small, expected delays in the timer) for some time.

但是,当计时器长时间运行(超过5分钟)时,触发之间会有类似的极端延迟(也是6-10秒.)看起来像是使用以下方法手动安排了计时器

But when the timer is running for a long time (more than 5 minutes), there are similar extreme delays between firing (also 6-10 seconds.) It looks like manually scheduling the timer with

[[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];

稍微推迟了该问题(使用[NSTimer scheduledTimer...]使该问题出现的时间比将其手动添加到运行循环时要早).

postpones the problem a bit (using [NSTimer scheduledTimer...] makes that problem appear sooner than when manually adding it to the runloop.)

这会造成很多麻烦,因为在此期间时钟未更新.

This causes a lot of trouble because the clock is not updating during that time.

我认为发生这种情况是因为macOS在某种程度上认为显示应用程序空闲"或不活动".

I assume this happens because macOS considers the display app "idle" or "inactive" in some way.

有没有办法防止,控制或规避这种行为?

Is there a way to prevent, control, or circumvent this behaviour?

推荐答案

这是 App Nap .展示应用可以执行以下操作以避免打n:

This is App Nap. The display app can do the following to avoid napping:

id activity = [[NSProcessInfo processInfo] beginActivityWithOptions:NSActivityUserInitiatedAllowingIdleSystemSleep reason:@"whatever"];

当它可以再次允许小睡时,您应该执行以下操作:

When it can allow napping again, you should do:

[[NSProcessInfo processInfo] endActivity:activity];

这篇关于防止NSTimer在后台应用中触发延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆