1

In my WP8 application I need to download some json data every 5 minutes.
But in MSDN it's written that periodic tasks are run every 30 minutes.

Are there any workarounds to run periodic tasks in background every 5 minutes?
Are there any other ways of doing that without periodic background tasks?

Currently I'm using Periodic task to download json data

Here is my code

public class ScheduledAgent : ScheduledTaskAgent
{
    public string Url { get; set; }
    private static FlightForNotificationDataModel _flightForNotificationData;
    private static NotificationDataViewModel _notificationData;

    public ObservableCollection<NotificationViewModel> Notifications { get; set; }
    /// <remarks>
    /// ScheduledAgent constructor, initializes the UnhandledException handler
    /// </remarks>
    static ScheduledAgent()
    {
        // Subscribe to the managed exception handler
        Deployment.Current.Dispatcher.BeginInvoke(delegate
        {
            Application.Current.UnhandledException += UnhandledException;
        });
        _flightForNotificationData = new FlightForNotificationDataModel("isostore:/tashkentAir.sdf");
        _notificationData = new NotificationDataViewModel("isostore:/tashkentAir.sdf");
    }

    /// Code to execute on Unhandled Exceptions
    private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
    {
        if (Debugger.IsAttached)
        {
            // An unhandled exception has occurred; break into the debugger
            Debugger.Break();
        }
    }

    /// <summary>
    /// Agent that runs a scheduled task
    /// </summary>
    /// <param name="task">
    /// The invoked task
    /// </param>
    /// <remarks>
    /// This method is called when a periodic or resource intensive task is invoked
    /// </remarks>
    protected override void OnInvoke(ScheduledTask task)
    {
        //TODO: Add code to perform your task in background
        //NotificationsViewModel notificationData = new NotificationsViewModel();
        //notificationData.GetData();
        GetData();

        Notifications = new ObservableCollection<NotificationViewModel>();
        //NotifyComplete();
    }

    private void GetData()
    {
        _flightForNotificationData.GenerateNotificationUrl();
        if (!String.IsNullOrEmpty(_flightForNotificationData.NotificationsUrl))
        {
            this.Url = _flightForNotificationData.NotificationsUrl;
            var task = new HttpGetTask<Notifications>(this.Url, OnPostExecute);

            task.Execute();
        }
        else
            return;
    }

    private void OnPostExecute(Notifications responseObject)
    {
        this.OnNotificationsDownloaded(responseObject);
        NotifyComplete();
    }

    private void OnNotificationsDownloaded(Notifications notifications)
    {
        if (string.IsNullOrEmpty(notifications.HasData))
        {
            Notifications.Clear();
            List<NotificationViewModel> notVMList = new List<NotificationViewModel>();

            foreach (TashkentAir.Models.Notification not in notifications.Notifications_)
            {
                NotificationViewModel notVM = new NotificationViewModel();
                notVM.Date = not.Date;
                notVM.Direction = not.Direction;
                notVM.Flight_ = not.Flight_;
                notVM.Time = not.Time;
                notVM.Timestamp = not.Timestamp;
                switch (not.Status)
                {
                    case 0:
                        notVM.Status = "Нет данных";
                        break;
                    case 1:
                        notVM.Status = "Прибыл";
                        _flightForNotificationData.DeleteFlightForNotification(not.FlightID);
                        break;
                    case 2:
                        notVM.Status = "Отправлен";
                        break;
                    case 3:
                        notVM.Status = "Регистрация";
                        break;
                    case 4:
                        notVM.Status = "Посадка";
                        break;
                    case 5:
                        notVM.Status = "Задержан";
                        break;
                    case 6:
                        notVM.Status = "Отменен";
                        break;
                    default:
                        notVM.Status = "";
                        break;
                }
                ShellToast toast = new ShellToast();
                toast.Title = notVM.Flight_;
                toast.Content = notVM.Status;
                toast.Show();
                notVMList.Add(notVM);
            }
            notVMList = notVMList.OrderBy(n => n.Timestamp).ToList();
            notVMList.ForEach(this.Notifications.Add);
            if (_notificationData == null)
                _notificationData = new NotificationDataViewModel("isostore:/tashkentAir.sdf");
            _notificationData.SaveJSONNotificationsToDB(Notifications);
        }
        else
        {
            _flightForNotificationData.ClearAllData();
            _notificationData.ClearAllData();
        }
    }
}

But this task runs every 30 minutes

Json data is data about flights and that information loses its actuality in that period

So, I need to make it run every 5 minutes or more frequently

How can I do that?

csharpwinphonexaml
  • 3,659
  • 10
  • 32
  • 63
Umriyaev
  • 1,150
  • 11
  • 17

3 Answers3

1

Sorry, you can't run a true background task more frequently than the standard intervals. You can, however, get the data as often as you like when the app is running in the foreground, but be aware that you might upset your users if there's a lot of data to pull.

ZombieSheep
  • 29,603
  • 12
  • 67
  • 114
0

I think this might be do your work.try this.

dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,5,0);
dispatcherTimer.Start();

And DispatcherTimer_Tick Method

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
      //Do your Method...
}

Go to MSDN Dispatcher Timer for more Details.

Harshana Narangoda
  • 775
  • 1
  • 8
  • 23
  • Will dispatcherTimer continue running in the background? Even if I close the application? – Umriyaev Apr 14 '14 at 12:40
  • WP7/Wp8 don't allow for full multitasking in the background for arbitrary apps. Whatever it is you're trying to accomplish will either have to be achieved in some other way or just not done on windows phone.Background agent do in every 30 mins because to save battery and keep phone healthy.in my code it will work on when the app run on foreground. Do you need to download data when after app is terminated? Look this thread for more details. http://stackoverflow.com/questions/13514064/how-to-run-application-in-background-in-windows-phone/13520869#13520869 – Harshana Narangoda Apr 14 '14 at 12:53
0

You can use push Notification, or rawnotification dependent on how much data is needed to be send. And when the app is in foreground you can accomplish what you want with a timer? But using background tasks is not possible.

Toast Notifications

Server Side

JTIM
  • 2,774
  • 1
  • 34
  • 74
  • Does push notification service require the notification server sends push notifications itself? Cuz in my case the server only responds to the http requests, and doesn't send notifications for itself – Umriyaev Apr 15 '14 at 08:09
  • This is something you have to implement, and then you can have your app listen to the push notification. And when it arrives display a message in the top as toast notification or a tile notification. And then upon login to the app you can acquire what you want from your server. And start the timer so that you can update everything in the period you want. I have added a link in my answer @Umriyaev – JTIM Apr 15 '14 at 08:12
  • But the server is already implemented, and as I said before, server doesn't send push notifications when the data is changed. So I have to request data in the background. As I said before, the data is about the flights and arrivals, and in 30 minutes it will loose it's actuality. That's why I'm asking for the another approach of getting data every 5 minutes or more frequently – Umriyaev Apr 15 '14 at 08:25
  • You can create a free azure server that "steals" or looks if changes occurs and sends the push notification to devices – JTIM Apr 15 '14 at 08:39
  • Could you show me example of it? Is using Azure free? – Umriyaev Apr 15 '14 at 13:01
  • Yes for a periode of time. Then you can register to Bizspark and get a free account for some years. There is many examples on Azure go here and watch movies which is benefit, http://channel9.msdn.com/Events/windowsazure/AzureConf2012?sort=rating&direction=asc#tab_sortBy_rating they link to other information. A vote up or a correct answer is allways appreciated :) – JTIM Apr 15 '14 at 13:09