标签: background-task

定期iOS后台位置更新

我正在编写一个需要高精度和低频率的背景位置更新的应用程序.该解决方案似乎是一个后台NSTimer任务,它启动位置管理器的更新,然后立即关闭.之前已经问过这个问题:

如何在iOS应用程序中每n分钟更新一次后台位置?

应用程序进入后台后每n分钟获取用户位置

iOS不是典型的后台位置跟踪计时器问题

iOS长时间运行的后台计时器,带有"位置"后台模式

基于位置跟踪的iOS全天候后台服务

但我还没有得到最起码的例子.在尝试了上述接受的答案的每一个排列后,我总结了一个起点.输入背景:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    self.bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        NSLog(@"ending background task");
        [[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
        self.bgTask = UIBackgroundTaskInvalid;
    }];


    self.timer = [NSTimer scheduledTimerWithTimeInterval:60
                                                  target:self.locationManager
                                                selector:@selector(startUpdatingLocation)
                                                userInfo:nil
                                                 repeats:YES];
}
Run Code Online (Sandbox Code Playgroud)

和委托方法:

- (void)locationManager:(CLLocationManager *)manager 
    didUpdateToLocation:(CLLocation *)newLocation 
           fromLocation:(CLLocation *)oldLocation {

    NSLog(@"%@", newLocation);

    NSLog(@"background time: %f", [UIApplication sharedApplication].backgroundTimeRemaining);
    [self.locationManager stopUpdatingLocation];

}
Run Code Online (Sandbox Code Playgroud)

当前行为是backgroundTimeRemaining从180秒减少到零(记录位置时),然后执行到期处理程序,不再生成进一步的位置更新.如何修改上述代码以便在后台无限期地接收定期位置更新

更新:我的目标是iOS 7,似乎有一些证据表明后台任务的行为有所不同:

从后台任务启动iOS 7中的位置管理器

objective-c core-location ios background-task ios-background-mode

91
推荐指数
4
解决办法
9万
查看次数

如何在启动时启动后台任务 - Windows应用商店应用

我的平板电脑运行Windows 8.1专业版.

它有一个后台任务,每15'由一个时间触发器触发.它很有效,很公平.

问题是我需要在设备的每次启动(启动应用程序)时自动启动后台任务.

我通过以下代码注册了我的bg:

       builder.Name = "bikePositionUpdate";
        builder.TaskEntryPoint = "BackgroundTaskGps.BikeGPSPositionUpdateBackgroundTask";
        builder.SetTrigger(new TimeTrigger(15, false)); // 

        // adding condition
        SystemCondition internetCondition = new SystemCondition(SystemConditionType.InternetAvailable);
        SystemCondition userPresentCondition = new SystemCondition(SystemConditionType.UserPresent); 

        builder.AddCondition(internetCondition);
        builder.AddCondition(userPresentCondition);
        BackgroundTaskRegistration taskRegistration = builder.Register();
Run Code Online (Sandbox Code Playgroud)

我的应用程序有锁屏访问

         await BackgroundExecutionManager.RequestAccessAsync();
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?我错过了什么吗?

c# windows-store-apps background-task

14
推荐指数
1
解决办法
1909
查看次数

'某些服务无法构建(验证服务描述符时出错'ServiceType:IHostedService

我正在使用 .NET 5,我想使用IHostedService类运行后台任务,如您所见:

public class PasargadJobs : IHostedService, IDisposable
{
    private Timer _timer = null!;
    readonly  ITerminalService _terminalService;
    readonly  IMessageService _messageService;
    readonly IMerchantService _merchantService;
    
    public PasargadJobs(
        IMerchantService merchantService,
        ITerminalService terminalService,
        IMessageService messageService)
    {
        _messageService = messageService;
        _terminalService = terminalService;
        _merchantService = merchantService;
    }
    
    //other parts of code are removed for short code
}
Run Code Online (Sandbox Code Playgroud)

所以我必须将它注入到服务集合中,如您所见:

services.AddHostedService<PasargadJobs>();
Run Code Online (Sandbox Code Playgroud)

但添加此后我收到此错误:

System.AggregateException:“无法构造某些服务(验证服务描述符时出错”ServiceType:Microsoft.Extensions.Hosting.IHostedService Lifetime:Singleton ImplementType:MIMS.Portal.ScheduleJobs.PasargadJobs”:无法使用作用域服务“Microsoft” .EntityFrameworkCore.DbContextOptions`1[MIMS.Portal.Infrustruct.Repositories.AppDbContext]'来自单例'Microsoft.Extensions.Hosting.IHostedService'。)'

这是我的startup.cs

services.AddExpressiveAnnotations();

//--- DB Context ---//
services.AddTransient<AppDbContext, AppDbContext>();
//--- Repositories ---//
services.AddTransient(typeof(IGenericRepository<>), typeof(GenericRepository<>));
services.AddTransient<IMerchantRepository, MerchantRepository>();
services.AddTransient<IBankAccountRepository, BankAccountRepository>();
services.AddTransient<IBankRepository, …
Run Code Online (Sandbox Code Playgroud)

dependency-injection background-task asp.net-core asp.net-core-hosted-services servicecollection

13
推荐指数
1
解决办法
5万
查看次数

继续在后台下载

我正在创建一个应用程序,其中我从服务器下载一些数据.在后台进行时,我希望连接应该继续运行,以便可以下载数据.我知道appDelegate中有方法

- (void)applicationDidEnterBackground:(UIApplication *)application  
Run Code Online (Sandbox Code Playgroud)

当应用程序进入后台时调用.但是,随着连接的viewController中创建的,怎么能在管理的appDelegate
还有/其他方式可以这样做吗?我已经通过这个链接,但是有一些简单的实现吗?

uiapplicationdelegate ios background-task

12
推荐指数
1
解决办法
6314
查看次数

iOS 13 - 不能一直使用 BGTaskScheduler

问题: 我想在应用程序进入后台 5 秒后运行一个简单的函数。

我必须实现BGTaskScheduler,以支持 iOS 13。 BackgroundTask 的旧实现适用于旧 iOS 版本。

我按要求添加了后台模式(勾选了 BLE 配件,因为我们在此功能中执行了一个小的 BLE 操作):

在此处输入图片说明

然后,我根据文档准备了 Info.plist(标识符是假的,仅用于 StackOverflow 问题):

在此处输入图片说明

didFinishLaunchingWithOptions结束之前,我注册了我的 BackgroundTask:

if #available(iOS 13.0, *) {
        BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.example.MyID", using: .global()) { (task) in
            print("My backgroundTask is executed NOW!")
            task.expirationHandler = {
                task.setTaskCompleted(success: true)
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在,当应用程序运行didEnterBackground方法时,我提交了一个 BackgroundTaskRequest:

if #available(iOS 13.0, *) {
            do {
                let request = BGAppRefreshTaskRequest(identifier: "com.example.MyID")
                request.earliestBeginDate = Calendar.current.date(byAdding: .second, value: 5, to: Date())
                try BGTaskScheduler.shared.submit(request)

                print("Submitted …
Run Code Online (Sandbox Code Playgroud)

ios swift background-task taskscheduler ios-background-mode

9
推荐指数
1
解决办法
7152
查看次数

Windows 10 UWP - 如果前台应用程序正在运行,则停止后台任务

如果正在执行前台应用程序,如何阻止后台任务运行?为我的应用程序使用通用Windows平台.

我的后台任务是检查某个站点上的新项目,并在有新的东西时发送一个Toast,但是如果用户现在正在运行应用程序,我不想阻止吐司发送.

我试图在我的应用程序启动时取消注册任务并在应用程序终止时再次注册,通过,这对我来说不是很好的解决方案 - 当设备由于某种原因关闭时(例如,电池被移除)我的任务将不会注册,直到应用再次启动

谢谢.

c# windows windows-phone background-task uwp

8
推荐指数
1
解决办法
5423
查看次数

WinRT中的后台任务回调(Cordova Windows插件)

我正在为Cordova制作插件,目前我正在尝试使其支持Windows平台.我有一个用C#编写的DLL,我想在我的插件中使用那里的功能.为了做到这一点,我创建了Windows运行时组件项目,该项目围绕C#DLL"包装",并从那里我将方法暴露给Cordova中的Java Script,我可以成功调用它们.所以,之间的沟通

App <-> Plugin <-> WinRT <-> C# DLL
Run Code Online (Sandbox Code Playgroud)

工作得很好.

在某些时候(在C#DLL中的一个方法中)我试图做以下事情:

Task.Factory.StartNew(() => ProcessQueue(), TaskCreationOptions.LongRunning);
Run Code Online (Sandbox Code Playgroud)

一旦代码执行到达这一部分,我得出结论,app只是默默地跳过这部分,ProcessQueue()方法永远不会开始在后台任务中执行.首先,我认为问题可能与我在C#中启动此任务的方式有关,所以我尝试了几个替换来启动新的后台任务 - 没有运气.

然后我想我可以从后台线程调用Java Script中的插件(我不是Cordova/Java Script专家,你可以从这个假设看到),但很快意识到它不会发生.我发现作为Cordova插件的一部分对本机代码进行的调用不是在主UI线程中执行,而是在其他一些线程中执行,但仍然无法在该线程中从C#DLL创建后台任务.

然后我阅读了WinRT组件中的后台任务并试图实现它.我使用这个项目作为参考:https://github.com/Microsoft/Windows-universal-samples/tree/93bdfb92b3da76f2e49c959807fc5643bf0940c9/Samples/BackgroundTask/cs/BackgroundTask

在该项目中,他们正在从C#app触发后台任务.我不知道如何从Cordova应用程序中执行此操作(甚至可以从那里执行此操作?),因此当从Java Script代理调用WinRT组件中的一个方法时,我尝试触发它.所以基本上,我的后台任务类存在于WinRT组件中(如示例中所示),但我是从WinRT而不是从应用程序触发它.当然,另一个区别是我使用Cordova应用程序的package.windows10.appxmanifest来注册后台任务.

执行此操作后,我没有编译错误,触发任务的代码工作并执行,但后台任务的Run方法永远不会被调用.

所以,我的问题是:有谁知道我怎么能完成这件事?如何在WinRT组件或Windows Cordova插件中一般启动后台任务?

非常感谢任何答案.

干杯


更新#1

好的,我设法解决了我的原始问题,这是代码.

我使用Dummy.cs类创建了WinRT组件,这是WinJS代码的入口点,它获取了我的一些自定义对象作为参数.类看起来像这样:

using System;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Runtime.Serialization;
using Windows.Foundation.Collections;
using Windows.ApplicationModel.Background;

namespace DummyWinRT
{
    public sealed class WRTDummy
    {
        private static ApplicationTrigger _trigger;

        public async static void MethodCalledFromWinJS(MyCustomObject myObject)
        {
            await BackgroundExecutionManager.RequestAccessAsync();

            foreach (var t in BackgroundTaskRegistration.AllTasks)
            {
                t.Value.Unregister(true);
            }

            _trigger …
Run Code Online (Sandbox Code Playgroud)

windows-phone cordova cordova-plugins background-task visual-studio-cordova

8
推荐指数
0
解决办法
629
查看次数

如何初始化全局对象或变量并在每个 FastAPI 端点中重用它?

我正在上一堂发送通知的课。初始化时,它涉及到与通知服务器的连接,这非常耗时。我在 FastAPI 中使用后台任务来发送通知,因为我不想因通知而延迟响应。下面是示例代码。

file1.py:
noticlient = NotificationClient()

@app.post("/{data}")
def send_msg(somemsg: str, background_tasks: BackgroundTasks):
    result = add_some_tasks(data, background_tasks, noticlient)
    return result

file2.py:
def add_some_tasks(data, background_tasks: BackgroundTasks, noticlient):
    background_tasks.add_task(noticlient.send, param1, param2)
    result = some_operation
    return result
Run Code Online (Sandbox Code Playgroud)

这里,通知客户端是全局声明的。我可以在file2.pyunder中初始化它add_some_tasks,但每次请求到达时它都会被初始化,这需要一些时间。有什么办法可以使用中间件在每次请求到达时重新使用它,这样就不需要每次都进行初始化。

或方法二:在类 def 中初始化通知

file1.py:
class childFastApi(FastAPI):
    noticlient = NotificationClient()

app = childFastApi()

@app.post("/{data}")
def send_msg(somemsg: str, background_tasks: BackgroundTasks):
    result = add_some_tasks(data, background_tasks, app.noticlient)
    return result
Run Code Online (Sandbox Code Playgroud)

python global-variables background-task starlette fastapi

8
推荐指数
1
解决办法
6145
查看次数

后台请求不执行Alamofire Swift

我试图在POST,GET等后台进行调用,以便在didReceiveRemoteNotification方法中更精确,因为它们开始作为推送通知到达.我的问题是,在我打开应用程序之前,所有Alamofire.request都不会在后台模式中调用.我现在有

我试图打开一个会话,但它不会使请求工作.

这些是我想在后台执行的(后台手机)

Alamofire.Manager(configuration: configuration).request(.GET, url, parameters: nil)
                        .responseJSON { (_, _, JSON, _) in
                            //println(JSON)
                                println(JSON)
                REST OF THE CODE 
Run Code Online (Sandbox Code Playgroud)

但是它不会起作用,即使我在这些请求下面添加代码也可以工作,但是请求的返回甚至是请求都没有.

uiapplicationdelegate swift background-task alamofire backgroundtaskidentifier

7
推荐指数
1
解决办法
4587
查看次数

如何在"django-background-tasks"中激活进程队列

我是Django和django-background-tasks软件包的新手.

我面临一个我无法做的问题/启动后台任务,除非我强行运行命令process_tasks,即python manage.py process_tasks.我想在不运行process_tasks命令的情况下执行/启动后台任务.

settings.py

MAX_ATTEMPTS=1
BACKGROUND_TASK_RUN_ASYNC = True
Run Code Online (Sandbox Code Playgroud)

tasks.py

from background_task import background
#included necessary packages for SMTP
@background(schedule=5)
def test():
    #send mail to some ids
Run Code Online (Sandbox Code Playgroud)

views.py

def index(request):
    test(schedule=5)
    return HttpResponse("Hello, world. ")
Run Code Online (Sandbox Code Playgroud)

忽略我的逻辑.

django multithreading python-2.7 background-task

7
推荐指数
2
解决办法
2574
查看次数