Search code examples
c#timerbackgroundwindows-phone-8.1background-task

Background timer function in WIndows phone 8.1


I'm developing windows phone 8.1 Application. I have timer function that works perfect in foreground. I need to send report every 30 seconds when Panic button is on.

Here is My Timer Class,

 public void Start_timer()
    {
        DispatcherTimer timer = new DispatcherTimer();
        timer.Tick += timer_Tick;
        timer.Interval = new TimeSpan(00, 0, 30);
        bool enabled = timer.IsEnabled;
        timer.Start();
    }

 async void timer_Tick(object sender, object e)
    {
        // string which collects data. 
       URL_log_string = device_id_string + "," + UTCdatetime + "," + lng + "," + lat + "," + speed + "," + heading + "," + alt + "," + "," + battery_level + "," + accuracy + "," + 1 + "," + "," + 0; 

       //Locally log storage 
       Log_Class_Object.Save_Data_in_Log("Panic Sent ", URL_log_string);
       URL_log_string = "";

    }

my background Class is to implement background task.

class Task_Class
{

    public sealed class ExampleBackgroundTask : IBackgroundTask
    {
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();

          //

            _deferral.Complete();
        }

    public static async Task<BackgroundTaskRegistration> RegisterBackgroundTask(String taskEntryPoint, String name, IBackgroundTrigger trigger, IBackgroundCondition condition)
       {
           foreach (var task in BackgroundTaskRegistration.AllTasks)
           {
               task.Value.Unregister(true);
           }
           await BackgroundExecutionManager.RequestAccessAsync();
           var builder = new BackgroundTaskBuilder();
           builder.Name = name;
           builder.TaskEntryPoint = taskEntryPoint;
           builder.SetTrigger(new TimeTrigger(15, false));
           //var ret = builder.Register();

           BackgroundTaskRegistration related_task = builder.Register();

           return related_task;
       }

   }
}

Here is My xmlmanifest screen shot.

enter image description here

I don't have idea how to call this timer class in background. Cooperation in this regard will highly be appreciated.


Solution

  • You cannot use DispatcherTimer in background task

    Use ThreadPoolTimer

        TimerElapsedHandler handler=function;
            ThreadPoolTimer.CreatePeriodicTimer(handler, TimeSpan.FromSeconds(30));
    
     async  private void function(ThreadPoolTimer timer)
            {
                URL_log_string = device_id_string + "," + UTCdatetime + "," + lng + "," + lat + "," + speed + "," + heading + "," + alt + "," + "," + battery_level + "," + accuracy + "," + 1 + "," + "," + 0; 
    
       //Locally log storage 
       Log_Class_Object.Save_Data_in_Log("Panic Sent ", URL_log_string);
       URL_log_string = "";
    
            }