【问题标题】:how to run periodic tasks every 5 minutes or more frequently in windows phone 8如何在 Windows Phone 8 中每 5 分钟或更频繁地运行定期任务
【发布时间】:2014-04-14 11:20:05
【问题描述】:

在我的 WP8 应用程序中,我需要每 5 分钟下载一些 json 数据。
但在 MSDN 中,定期任务每 30 分钟运行一次。

是否有任何解决方法可以每 5 分钟在后台运行定期任务?
在没有定期后台任务的情况下,还有其他方法可以做到这一点吗?

目前我正在使用定期任务来下载 json 数据

这是我的代码

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();
        }
    }
}

但此任务每 30 分钟运行一次

Json 数据是有关航班的数据,并且该信息在该期间失去了真实性

所以,我需要让它每 5 分钟或更频繁地运行一次

我该怎么做?

【问题讨论】:

    标签: c# windows-phone-8


    【解决方案1】:

    抱歉,您不能比标准间隔更频繁地运行真正的后台任务。但是,当应用程序在前台运行时,您可以随意获取数据,但请注意,如果要提取大量数据,您可能会让用户感到不安。

    【讨论】:

      【解决方案2】:

      您可以根据需要发送多少数据来使用推送通知或原始通知。当应用程序处于前台时,您可以使用计时器完成您想要的事情吗? 但无法使用后台任务。

      Toast Notifications

      Server Side

      【讨论】:

      • 推送通知服务是否需要通知服务器自己发送推送通知?因为在我的情况下,服务器只响应 http 请求,并且不会为自己发送通知
      • 这是你必须实现的东西,然后你可以让你的应用程序监听推送通知。当它到达时,在顶部显示一条消息作为 toast 通知或磁贴通知。然后在登录到应用程序后,您可以从服务器获取您想要的内容。并启动计时器,以便您可以在所需的时间段内更新所有内容。我在答案中添加了一个链接@Umriyaev
      • 但是服务端已经实现了,而且我之前说过,当数据发生变化时,服务端不会发送推送通知。所以我必须在后台请求数据。正如我之前所说,这些数据是关于航班和到达的,并且在 30 分钟内就会失去它的真实性。这就是为什么我要求另一种方法,即每 5 分钟或更频繁地获取数据
      • 您可以创建一个免费的 azure 服务器,“窃取”或查看是否发生更改并将推送通知发送到设备
      • 你能给我看看它的例子吗?使用 Azure 免费吗?
      【解决方案3】:

      我认为这可能是你的工作。试试这个。

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

      和 DispatcherTimer_Tick 方法

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

      请访问 MSDN Dispatcher Timer 了解更多详情。

      【讨论】:

      • dispatcherTimer 会继续在后台运行吗?即使我关闭应用程序?
      • WP7/Wp8 不允许在后台对任意应用程序进行完整的多任务处理。无论您要完成什么,都必须以其他方式实现,或者只是不在 Windows Phone 上完成。后台代理每 30 分钟执行一次,因为为了节省电池并保持手机健康。在我的代码中,它将运行当应用程序在前台运行时。应用程序终止后是否需要下载数据?查看此线程以获取更多详细信息。 stackoverflow.com/questions/13514064/…
      猜你喜欢
      • 2011-06-08
      • 2021-02-15
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 2014-12-29
      • 1970-01-01
      相关资源
      最近更新 更多