C# 如何在windows phone 8中每隔5分钟或更频繁地运行定期任务

C# 如何在windows phone 8中每隔5分钟或更频繁地运行定期任务,c#,windows-phone-8,C#,Windows Phone 8,在我的WP8应用程序中,我需要每5分钟下载一些json数据。 但在MSDN中,有人写道周期性任务每30分钟运行一次 每5分钟在后台运行定期任务是否有解决方法? 在没有定期背景任务的情况下,还有其他方法可以做到这一点吗 目前我正在使用定期任务下载json数据 这是我的密码 public class ScheduledAgent : ScheduledTaskAgent { public string Url { get; set; } private static FlightFo

在我的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();
        }
    }
}
公共类ScheduledAgent:ScheduledTaskAgent
{
公共字符串Url{get;set;}
私有静态FlightForNotificationDataModel_flightForNotificationData;
私有静态NotificationDataViewModel_notificationData;
公共ObservableCollection通知{get;set;}
/// 
///ScheduledAgent构造函数,初始化未处理的异常处理程序
/// 
静态调度
{
//订阅托管异常处理程序
Deployment.Current.Dispatcher.BeginInvoke(委托
{
Application.Current.UnhandledException+=未处理的异常;
});
_flightForNotificationData=新的FlightForNotificationDataModel(“isostore:/tashkentAir.sdf”);
_notificationData=新NotificationDataViewModel(“isostore:/tashkentAir.sdf”);
}
///要在未处理的异常上执行的代码
私有静态void UnhandledException(对象发送方、应用程序unhandledExceptionEventArgs e)
{
if(Debugger.IsAttached)
{
//发生未处理的异常;请中断调试器
Debugger.Break();
}
}
/// 
///运行计划任务的代理
/// 
/// 
///被调用的任务
/// 
/// 
///在调用周期性或资源密集型任务时调用此方法
/// 
受保护的覆盖无效OnInvoke(ScheduledTask任务)
{
//TODO:添加代码以在后台执行任务
//NotificationsViewModel notificationData=新的NotificationsViewModel();
//notificationData.GetData();
GetData();
通知=新的ObservableCollection();
//NotifyComplete();
}
私有void GetData()
{
_flightForNotificationData.GenerateNotificationUrl();
如果(!String.IsNullOrEmpty(_flightForNotificationData.NotificationsUrl))
{
this.Url=\u flightForNotificationData.NotificationsUrl;
var task=newhttpgettask(this.Url,OnPostExecute);
task.Execute();
}
其他的
返回;
}
私有void OnPostExecute(通知响应对象)
{
此.onNotificationsDownload(响应对象);
NotifyComplete();
}
私有void onnotificationsdownload(通知)
{
if(string.IsNullOrEmpty(notifications.HasData))
{
通知。清除();
List notVMList=新列表();
foreach(TashkentAir.Models.Notification不在notifications.notifications中)
{
NotificationViewModel notVM=新建NotificationViewModel();
notVM.Date=not.Date;
notVM.Direction=not.Direction;
notVM.Flight=not.Flight;
notVM.Time=not.Time;
notVM.Timestamp=not.Timestamp;
开关(非。状态)
{
案例0:
notVM.Status=“аааааааф”;
打破
案例1:
notVM.Status=“Пбб”;
_flightForNotificationData.DeleteFlightForNotification(非.FlightID);
打破
案例2:
notVM.Status=“ааааа”;
打破
案例3:
notVM.Status=“ааааааа”;
打破
案例4:
notVM.Status=“ПСаааа”;
打破
案例5:
notVM.Status=“ажжжа”;
打破
案例6:
notVM.Status=“ццццц”;
打破
违约:
notVM.Status=“”;
打破
}
ShellToast toast=新的ShellToast();
toast.Title=notVM.Flight\u;
toast.Content=notVM.Status;
toast.Show();
notVMList.Add(notVM);
}
notVMList=notVMList.OrderBy(n=>n.Timestamp.ToList();
notVMList.ForEach(this.Notifications.Add);
如果(_notificationData==null)
_notificationData=新NotificationDataViewModel(“isostore:/tashkentAir.sdf”);
_notificationData.SaveJSONNotificationsToDB(通知);
}
其他的
{
_flightForNotificationData.ClearAllData();
_notificationData.ClearAllData();
}
}
}
但此任务每30分钟运行一次

Json数据是关于航班的数据,而这些信息在这段时间内失去了它的真实性

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


我该怎么做呢?

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

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

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

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

有关详细信息,请转到MSDN Dispatcher Timer。

根据需要发送的数据量,您可以使用推送通知或RAW通知。当应用程序位于前台时,您可以完成以下操作: