Exemplo n.º 1
0
 private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) {
     if(FirstLoad) {
         FirstLoad = false;
         MainPivot.SelectionChanged += MainPivot_SelectionChanged;
         if(NetworkInterface.GetIsNetworkAvailable()) {
             if((DataContext as Settings).ComicList.Count == 0) {
                 try {
                     (DataContext as Settings).ComicList.Add(await XkcdInterface.GetCurrentComic());
                     System.Diagnostics.Debug.WriteLine((DataContext as Settings).ComicList.Count);
                 } catch(WebException) {
                     ShowNotification("Comic couldn't be loaded", 4000);
                 }
             } else {
                 GetNewerComics();
             }
             if(ScheduledActionService.Find(BackgroundTaskName) == null) {
                 var task = new PeriodicTask(BackgroundTaskName) {
                     Description = "Gets the number of new comics from xkcd"
                 };
                 try {
                     ScheduledActionService.Add(task);
                 } catch(InvalidOperationException) { }
             }
         } else {
             ShowNotification(NoNetworkMessage, 4000);
         }
     }
 }
Exemplo n.º 2
0
 public static void AddTask(string taskName, string description)
 {
     RemoveTask(taskName);
     PeriodicTask task = new PeriodicTask(taskName);
     task.Description = description;
     ScheduledActionService.Add(task);
 }
Exemplo n.º 3
0
 public Task()
 {
     periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
     #if DEBUG
     if (periodicTask != null)
     {
         ScheduledActionService.Remove(periodicTaskName);
         periodicTask = null;
     }
     #endif
     if (periodicTask == null)
     {
         periodicTask = new PeriodicTask(periodicTaskName);
         periodicTask.Description = "Sparklr notification agent";
         try
         {
             ScheduledActionService.Add(periodicTask);
         }
         catch (Exception ex)
         {
             //TODO: Handle errors here (For example if there are too many background tasks already)
         }
     }
     // If debugging is enabled, use LaunchForTest to launch the agent in 15 seconds.
     #if DEBUG
     ScheduledActionService.LaunchForTest(periodicTaskName, new TimeSpan(0, 0, 15));
     #endif
 }
Exemplo n.º 4
0
        public async void StartLockScreenImageChange()
        {
            var photolen = IsolatedStorageSettings.ApplicationSettings["navchk"] as string;

            if (photolen != "0")
            {
                var taskName = "my task";
                if (ScheduledActionService.Find(taskName) != null)
                {
                    ScheduledActionService.Remove(taskName);
                }
                var periodicTask = new PeriodicTask(taskName)
                {
                    Description = "some desc"
                };
                try
                {
                    ScheduledActionService.Add(periodicTask);
                    ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(10));
                }
                catch
                {
                    //handle
                }
            }
        }
Exemplo n.º 5
0
        public static void StartPeriodicAgent()
        {
            string       periodicTaskName = "OcellPeriodicTask";
            PeriodicTask periodicTask     = null;

            try
            {
                periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
            }
            catch (Exception)
            {
            }

            if (periodicTask != null)
            {
                RemoveAgent(periodicTaskName);
            }

            periodicTask             = new PeriodicTask(periodicTaskName);
            periodicTask.Description = "Updates live tile, sends scheduled tweets.";

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                try
                {
                    ScheduledActionService.Add(periodicTask);
                    ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(30));
                }
                catch (Exception)
                {
                }
            });
        }
        /// <summary>
        /// Call this to add the background task to update the live tile.
        /// </summary>
        /// <returns></returns>
        public static bool Add()
        {
            PeriodicTask periodicTask = new PeriodicTask(ShakingHelper.PeriodicTaskName);

            periodicTask.Description = AppResources.LiveTileTaskDescription;
            periodicTask.ExpirationTime = System.DateTime.Now.AddDays(14);

            // If the agent is already registered with the system,
            if (ScheduledActionService.Find(periodicTask.Name) != null)
            {
                ScheduledActionService.Remove(ShakingHelper.PeriodicTaskName);
            }

            //only can be called when application is running in foreground
            try
            {
                ScheduledActionService.Add(periodicTask);
            #if DEBUG
                ScheduledActionService.LaunchForTest(periodicTask.Name, TimeSpan.FromSeconds(60));
            #endif
            }
            catch (InvalidOperationException)
            {
                return false;
            }
            return true;
        }
Exemplo n.º 7
0
        /// <summary>
        /// http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh202942(v=vs.105).aspx
        ///
        /// </summary>
        private static void TryInitBackgroundTask()
        {
            try {
                var task  = ScheduledActionService.Find(BackgroundTaskName) as PeriodicTask;
                var found = task != null;
                if (!found)
                {
                    task = new PeriodicTask(BackgroundTaskName);
                }
                // shown in WP8 under Settings -> applications -> background tasks -> MusicPimp
                task.Description    = "Updates the live tiles with album covers if available. Also updates the lock screen background if enabled.";
                task.ExpirationTime = DateTime.Now.AddDays(14);
                try {
                    if (found)
                    {
                        ScheduledActionService.Remove(BackgroundTaskName);
                    }
                    ScheduledActionService.Add(task);
                } catch (InvalidOperationException) {
                    /// If you attempt to add a periodic background agent when the device’s limit has been exceeded,
                    /// the call to Add(ScheduledAction) will throw an InvalidOperationException.
                    ///
                    /// If agents have been disabled for your app, attempts to register an agent using the
                    /// Add(ScheduledAction) method of the ScheduledActionService will throw an InvalidOperationException.
                } catch (SchedulerServiceException) {
                    /// A SchedulerServiceException can also be thrown when adding a task, for example,
                    /// if the device has just booted and the Scheduled Action Service hasn’t started yet.
                }
            } catch (Exception) { }


            //#if DEBUG_AGENT
            //                ScheduledActionService.LaunchForTest(BackgroundTaskName, TimeSpan.FromSeconds(10));
            //#endif
        }
        public static void PeriodicTileUpdater()
        {
            var periodicTask = ScheduledActionService.Find(TaskName) as PeriodicTask;

            if ( periodicTask != null )
            {
                ScheduledActionService.Remove(TaskName);
            }

            periodicTask = new PeriodicTask(TaskName)
            {
                Description = "Periodic Task to Update the ApplicationTile"
            };

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(periodicTask);

                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
                //ScheduledActionService.LaunchForTest(TaskName, TimeSpan.FromSeconds(10));
            }
            catch ( InvalidOperationException ex )
            {
                Debug.WriteLine(ex.Message);
            }
        }
Exemplo n.º 9
0
        private void StartPeriodicAgent()
        {
            AgentIsEnabled = true;

            // If this task already exists, remove it
            periodicTask = ScheduledActionService.Find( periodicTaskName ) as PeriodicTask;
            if (periodicTask != null)
            {
                RemoveAgent( periodicTaskName );
            }

            periodicTask = new PeriodicTask( periodicTaskName );
            periodicTask.Description = "This demonstrates a periodic task.";

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add( periodicTask );
                PeriodicStackPanel.DataContext = periodicTask;

                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if(DEBUG_AGENT)
                ScheduledActionService.LaunchForTest( periodicTaskName, TimeSpan.FromSeconds( 20 ) );
#endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains( "BNS Error: The action is disabled" ))
                {
                    MessageBox.Show( "Background agents for this application have been disabled by the user." );
                    AgentIsEnabled = false;
                    PeriodicCheckBox.IsChecked = false;
                }
            }
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            _periodicTask = ScheduledActionService.Find(PeriodicTaskName) as PeriodicTask;

            btnDisableLiveTileUpdate.IsEnabled = (_periodicTask != null);
            btnEnableLiveTileUpdate.IsEnabled = (_periodicTask == null);
        }
Exemplo n.º 11
0
        private void EnableLiveTileUpdateTask(object sender, RoutedEventArgs e)
        {
            _periodicTask = ScheduledActionService.Find(PeriodicTaskName) as PeriodicTask;

            if (_periodicTask != null)
            {
                RemoveAgent(PeriodicTaskName);
            }

            _periodicTask = new PeriodicTask(PeriodicTaskName);

            _periodicTask.Description = "JEVGENIDOTNET live tile update task";

            try
            {
                ScheduledActionService.Add(_periodicTask);

                #if DEBUG
                ScheduledActionService.LaunchForTest(PeriodicTaskName, TimeSpan.FromSeconds(30));
                #endif

                btnDisableLiveTileUpdate.IsEnabled = true;
                btnEnableLiveTileUpdate.IsEnabled  = false;
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show("Background agents for this application have been disabled by the user.");
                }
            }
        }
Exemplo n.º 12
0
        public void CreatePeriodicTask(string name)
        {
            var task = new PeriodicTask(name)
            {
                Description    = "Live tile updater for Happenings",
                ExpirationTime = DateTime.Now.AddDays(14)
            };

            RemovePeriodicTask(task.Name);

            try
            {
                // Can only be called when application is running in foreground
                ScheduledActionService.Add(task);
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show(AppResources.BackgroundAgentsDisabled);
                }
                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    // No user action required.
                    // The system prompts the user when the hard limit of periodic tasks has been reached.
                }
            }

            //#if DEBUG
            //ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(60));
            //#endif
        }
        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            // A unique name for the task. 
            var taskName = "Contoso Cookbook Community Updates";

            // If the task exists
            var oldTask = ScheduledActionService.Find(taskName) as PeriodicTask;
            if (oldTask != null)
            {
                ScheduledActionService.Remove(taskName);
            }

            // Create the Task
            PeriodicTask task = new PeriodicTask(taskName);

            // Description is required
            task.Description = "This looks for data on recipes shared by your community on Contoso Cookbook";

            // Add it to the service to execute
            ScheduledActionService.Add(task);

            // For debugging
            ScheduledActionService.LaunchForTest(taskName,  TimeSpan.FromMilliseconds(5000));


        }
Exemplo n.º 14
0
        private ScheduledAction AddBackgroundTask()
        {
            // Start background agent
            PeriodicTask periodicTask = new PeriodicTask(TASK_AGENT_NAME);

            periodicTask.Description = "Winsana background task";

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                // only can be called when application is running in foreground.
                ScheduledActionService.Add(periodicTask);

                return(periodicTask);
            }
            catch (InvalidOperationException ex)
            {
                if (ex.Message.Contains("BNS Error: The action is disabled"))
                {
                    Debug.WriteLine("Unable to start service agent");
                }
                if (ex.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    Debug.WriteLine("Unable to start service agent");
                }
            }
            catch (SchedulerServiceException ex)
            {
                Debug.WriteLine("Unable to start service agent");
            }

            return(null);
        }
Exemplo n.º 15
0
        private void StartPeriodicAgent()
        {
            periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;

            // If the task already exists and the IsEnabled property is false, background
            // agents have been disabled by the user
            if (periodicTask != null && !periodicTask.IsEnabled)
            {
                MessageBox.Show("Background agents for this application have been disabled by the user.");
                return;
            }

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update
            // the schedule
            if (periodicTask != null && periodicTask.IsEnabled)
            {
                RemoveAgent(periodicTaskName);
            }

            periodicTask = new PeriodicTask(periodicTaskName);

            // The description is required for periodic agents. This is the string that the user
            // will see in the background services Settings page on the device.
            periodicTask.Description = "This demonstrates a periodic task.";
            ScheduledActionService.Add(periodicTask);

            PeriodicStackPanel.DataContext = periodicTask;

            // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if (DEBUG_AGENT)
            ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(60));
#endif
        }
Exemplo n.º 16
0
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            // Display the default instructions.
            agentDetails.Text = defaultTaskDesc;

            // Find running periodic task.
            tilePeriodicTask = ScheduledActionService.Find(tileTaskName) as PeriodicTask;

            // Update the UI based on the running periodic task.
            if (toastPeriodicTask != null)
            {
                // Update the UI to display the currently running toast task info.
                PeriodicStackPanel.DataContext = toastPeriodicTask;
                TileRadioBtnOption.IsEnabled = false;
                startStopButton.Content = stopAgentString;
            }

            else if (tilePeriodicTask != null)
            {
                // Update the UI to display the currently running Tile task info.
                PeriodicStackPanel.DataContext = tilePeriodicTask;
                TileRadioBtnOption.IsChecked = true;
                TileRadioBtnOption.IsEnabled = false;
                startStopButton.Content = stopAgentString;
                agentDetails.Text = tileAgentDetails;
            }
            else
            {
                // No running task is running. Select Tile radio button.
                TileRadioBtnOption.IsChecked = true;
            }
        }
Exemplo n.º 17
0
        private void startStopButton_Click(object sender, RoutedEventArgs e)
        {
            // Find a reference to each of the two possibe periodic agents.
            tilePeriodicTask = ScheduledActionService.Find(tileTaskName) as PeriodicTask;

            // If either periodic agent is running, end it.
            // Otherwise, run the periodic agent based on the radio
            // button selection.
            if ((tilePeriodicTask != null))
            {

                // If the Tile periodic task is running, end it.
                if (tilePeriodicTask != null)
                {
                    RemoveAgent(tileTaskName);
                }
            }
            else
            {
                // Run the periodic agent based on the radio button selection.
                if ((bool)TileRadioBtnOption.IsChecked)
                {
                    StartPeriodicAgent(tileTaskName);
                    agentDetails.Text = tileAgentDetails;
                }
                else
                {
                    MessageBoxResult result = MessageBox.Show(startStopButtonMessage);
                }
            }
        }
Exemplo n.º 18
0
        public void CreatePeriodicTask(string name)
        {
            var task = new PeriodicTask(name)
                    {
                        Description = "Live tile updater for Weeker",
                        ExpirationTime = DateTime.Now.AddDays(14)
                    };

            // If the agent is already registered, remove it and then add it again
            RemovePeriodicTask(task.Name);

            try
            {
                // Can only be called when application is running in foreground
                ScheduledActionService.Add(task);
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show(Resource.BackgroundAgentsDisabled);
                }
                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    // No user action required.
                    // The system prompts the user when the hard limit of periodic tasks has been reached.
                }
            }
            #if DEBUG_AGENT
            ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(60));
            #endif
        }
Exemplo n.º 19
0
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            _periodicTask = ScheduledActionService.Find(PeriodicTaskName) as PeriodicTask;

            btnDisableLiveTileUpdate.IsEnabled = (_periodicTask != null);
            btnEnableLiveTileUpdate.IsEnabled  = (_periodicTask == null);
        }
Exemplo n.º 20
0
        public void StartPeriodicAgent()
        {
            agentsAreEnabled = true;
            periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
            if (periodicTask != null)
            {
                RemoveAgent(periodicTaskName);
            }

            periodicTask = new PeriodicTask(periodicTaskName);
            periodicTask.Description = "This demonstrates a periodic task.";

            try
            {
                ScheduledActionService.Add(periodicTask);
                ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(20));
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show("Background agents for this application have been disabled by the user.");
                    agentsAreEnabled = false;
                }

                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached.
                }
            }
            catch (SchedulerServiceException)
            {
                // No user action required.
            }
        }
Exemplo n.º 21
0
        public static void AddBGTaks()
        {
            PeriodicTask periodicTask = new PeriodicTask("BF3Stats");
            periodicTask.Description = "Gets stats in background hourly";

            try
            {
                if (ScheduledActionService.Find(periodicTask.Name) != null)
                {
                    ScheduledActionService.Remove("BF3Stats");
                }
                ScheduledActionService.Add(periodicTask);
            }
            catch (InvalidOperationException ex)
            {
                if (ex.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show("Background agents for this application have been disabled by the user.");
                }

                if (ex.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached.
                }
            }

        }
        private void EnableLiveTileUpdateTask(object sender, RoutedEventArgs e)
        {
            _periodicTask = ScheduledActionService.Find(PeriodicTaskName) as PeriodicTask;

            if (_periodicTask != null)
            {
                RemoveAgent(PeriodicTaskName);
            }

            _periodicTask = new PeriodicTask(PeriodicTaskName);

            _periodicTask.Description = "JEVGENIDOTNET live tile update task";

            try
            {
                ScheduledActionService.Add(_periodicTask);

                #if DEBUG
                ScheduledActionService.LaunchForTest(PeriodicTaskName, TimeSpan.FromSeconds(30));
                #endif

                btnDisableLiveTileUpdate.IsEnabled = true;
                btnEnableLiveTileUpdate.IsEnabled = false;
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show("Background agents for this application have been disabled by the user.");
                }
            }
        }
Exemplo n.º 23
0
        public static void StartTaskAgent()
        {
            PeriodicTask task =
                ScheduledActionService.Find(TaskName) as PeriodicTask;

            if (task != null)
            {
                RemoveAgent(TaskName);
            }

            task             = new PeriodicTask(TaskName);
            task.Description = "Screen Tile description";

            try
            {
                ScheduledActionService.Add(task);

#if (DEBUG_AGENT)
                ScheduledActionService.LaunchForTest(TaskName, TimeSpan.FromSeconds(20));
#endif
            }
            catch (InvalidOperationException e)
            {
                Debug.WriteLine(e.Message);
            }
        }
Exemplo n.º 24
0
        public static void StartPeriodicAgent()
        {
            string periodicTaskName = "OcellPeriodicTask";
            PeriodicTask periodicTask = null;

            try
            {
                 periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;

            }
            catch (Exception)
            {
            }

            if (periodicTask != null)
            {
                RemoveAgent(periodicTaskName);
            }

            periodicTask = new PeriodicTask(periodicTaskName);
            periodicTask.Description = "Updates live tile, sends scheduled tweets.";

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                try
                {
                    ScheduledActionService.Add(periodicTask);
                    ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(30));
                }
                catch (Exception)
                {
                }
            });
        }
        private void btnIniciaLog_Click(object sender, RoutedEventArgs e)
        {
            _periodicaTask = (ScheduledActionService.Find(_periodicTaskName) as PeriodicTask);

            //Se ela exite e nao esta habilitada
            if(_periodicaTask != null && !_periodicaTask.IsEnabled)
            {
                MessageBox.Show("Este background agent esta desabilitado pelo usuario");
                return;
            }

            //conseguiu encontrar a task e ela esta habilitada
            if (_periodicaTask != null && _periodicaTask.IsEnabled)
            {
                ScheduledActionService.Remove(_periodicTaskName);
            }

            _periodicaTask = new PeriodicTask(_periodicTaskName);
            _periodicaTask.Description = "Esta eh a descricao da task";
            _periodicaTask.ExpirationTime = DateTime.Now.AddDays(14);// o maximo que aceita é 14 dias de prorrogação 2 semanas

            ScheduledActionService.Add(_periodicaTask);

            #if(DEBUG_AGENT)
                    ScheduledActionService.LaunchForTest(_periodicTaskName,TimeSpan.FromSeconds(2));                
            #endif
        }
        private void StartTracking()
        {
            string tileTaskId = "PodcastStarterKitPlaybackAudioAgent";

            tileTask = ScheduledActionService.Find(tileTaskId) as PeriodicTask;
            
            if (tileTask != null && !tileTask.IsEnabled)
            {
                MessageBox.Show("Background agent for this application has been disabled by the user.");
                return;
            }

            if (tileTask != null && tileTask.IsEnabled)
            {
                RemoveAgent(tileTaskId);
            }

            tileTask = new PeriodicTask(tileTaskId);

            tileTask.Description = "New Poscast Finder";
            ScheduledActionService.Add(tileTask);

         
            // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
            #if(DEBUG)
            ScheduledActionService.LaunchForTest(tileTaskId, TimeSpan.FromSeconds(60));
            #endif
        }
Exemplo n.º 27
0
        private void InitTileUpdateTask()
        {
            const string taskName = "ScheduledAgent";

            TryRemoveTask(taskName);
            var action = new PeriodicTask(taskName)
            {
                Description = "Some description"
            };
            try
            {
                ScheduledActionService.Add(action);
                #if DEBUG_AGENT
                    ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(10));
                #endif
            }
            catch (InvalidOperationException)
            {
                TryRemoveTask(taskName);
            }
            catch (SchedulerServiceException)
            {
                TryRemoveTask(taskName);
            }
        }
Exemplo n.º 28
0
        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            string taskName = "AroundMeLockScreenChanger";
            //string taskName = "AroundMeLockScreenChangerTask";

            PeriodicTask oldTask = ScheduledActionService.Find(taskName) as PeriodicTask;

            if (oldTask != null)
            {
                ScheduledActionService.Remove(taskName);
            }

            // IMPORTANT: You'll get an error in the very next line of code
            // unless you add this to the WMAppManifest.xml beneath <DefaultTask>
            // in the <Tasks> section:

            /*
             *    <ExtendedTask Name="AroundMeLockScreenChangerTask">
             *      <BackgroundServiceAgent Specifier="ScheduledTaskAgent" Name="AroundMeLockScreenChanger" Source="AroundMe.Scheduler" Type="AroundMe.Scheduler.ScheduledAgent" />
             *    </ExtendedTask>
             */

            PeriodicTask task = new PeriodicTask(taskName);

            task.Description = "Change lockscreen wallpaper";

            ScheduledActionService.Add(task);

            //ScheduledActionService.LaunchForTest(task.Name,TimeSpan.FromSeconds(10));
        }
Exemplo n.º 29
0
        /// <summary>
        /// 启动
        /// </summary>
        public static void Start()
        {
            if (!AppSetting.IsScheduledAgent)
            {
                return;
            }

            if (isAgentOn)
            {
                return;
            }
            Stop();

            var periodicTask = new PeriodicTask(Params.PeriodicTaskName);

            periodicTask.Description = "腾讯微博客户端Altman后台任务,用于帮助用户检查是否有新微博,您可以在应用设置选项中将其关闭或者在手机的后台任务界面停止它。";

            try
            {
                ScheduledActionService.Add(periodicTask);
                //ScheduledActionService.LaunchForTest(Common.Params.PeriodicTaskName, TimeSpan.FromSeconds(2));
                isAgentOn = true;
            }
            catch { isAgentOn = false; }
        }
Exemplo n.º 30
0
        /// <summary>
        /// 启动
        /// </summary>
        public static void Start()
        {
            if (!AppSetting.IsScheduledAgent)
            {
                return;
            }

            if (isAgentOn)
            {
                return;
            }
            Stop();

            var periodicTask = new PeriodicTask(Params.PeriodicTaskName);

            periodicTask.Description = "腾讯微博客户端Altman后台任务,用于帮助用户检查是否有新微博,您可以在应用设置选项中将其关闭或者在手机的后台任务界面停止它。";

            try
            {
                ScheduledActionService.Add(periodicTask);
                //ScheduledActionService.LaunchForTest(Common.Params.PeriodicTaskName, TimeSpan.FromSeconds(2));
                isAgentOn = true;
            }
            catch { isAgentOn = false; }
        }
Exemplo n.º 31
0
        public void Start(TimeSpan scrapingInterval, TimeSpan uploadInterval)
        {
            this.scrape = new PeriodicTask(this.Scrape, scrapingInterval, scrapingInterval, Log, "Metrics Scrape");
            TimeSpan uploadJitter = new TimeSpan((long)(uploadInterval.Ticks * new Random().NextDouble()));

            this.upload = new PeriodicTask(this.Upload, uploadJitter, uploadInterval, Log, "Metrics Upload");
        }
Exemplo n.º 32
0
        public static void StartTaskAgent()
        {
            PeriodicTask task = 
                ScheduledActionService.Find(TaskName) as PeriodicTask;
            if (task != null)
            {
                RemoveAgent(TaskName);
            }

            task = new PeriodicTask(TaskName);
            task.Description = "Screen Tile description";

            try
            {
                ScheduledActionService.Add(task);

#if(DEBUG_AGENT)
                ScheduledActionService.LaunchForTest(TaskName, TimeSpan.FromSeconds(20));
#endif
            }
            catch (InvalidOperationException e)
            {
                Debug.WriteLine(e.Message);
            }
        }
Exemplo n.º 33
0
        /// <summary>
        /// Creates or renews the periodic agent on the scheduler.
        /// </summary>
        /// <returns>Whether the periodic agent is created or not</returns>
        public bool StartPeriodicAgent()
        {
            periodicDownload = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
            bool wasAdded = true;

            // If the task already exists and the IsEnabled property is false, then background
            // agents have been disabled by the user.
            if (periodicDownload != null && !periodicDownload.IsEnabled)
            {
                // Can't add the agent. Return false!
                wasAdded = false;
            }

            // If the task already exists and background agents are enabled for the
            // application, then remove the agent and add again to update the scheduler.
            if (periodicDownload != null && periodicDownload.IsEnabled)
            {
                ScheduledActionService.Remove(periodicTaskName);
            }

            periodicDownload             = new PeriodicTask(periodicTaskName);
            periodicDownload.Description = "Allows FeedCast to download new articles on a regular schedule.";
            ScheduledActionService.Add(periodicDownload);

            // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if (DEBUG_AGENT)
            ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(60));
#endif
            return(wasAdded);
        }
Exemplo n.º 34
0
        public TimersControlCenter()
        {
            cancellationToken = new CancellationToken();

            // Do NOT await!
            PeriodicTask.Run(CheckRelayTimers, new TimeSpan(0, 0, 10), cancellationToken);
        }
Exemplo n.º 35
0
        public AvailabilityMetrics(IMetricsProvider metricsProvider, string storageFolder, ISystemTime time = null)
        {
            this.systemTime     = time ?? SystemTime.Instance;
            this.availabilities = new List <Availability>();
            this.edgeAgent      = new Lazy <Availability>(() => new Availability(Constants.EdgeAgentModuleName, this.CalculateEdgeAgentDowntime(), this.systemTime));

            Preconditions.CheckNotNull(metricsProvider, nameof(metricsProvider));
            this.running = metricsProvider.CreateGauge(
                "total_time_running_correctly_seconds",
                "The amount of time the module was specified in the deployment and was in the running state",
                new List <string> {
                "module_name"
            });

            this.expectedRunning = metricsProvider.CreateGauge(
                "total_time_expected_running_seconds",
                "The amount of time the module was specified in the deployment",
                new List <string> {
                "module_name"
            });

            string storageDirectory = Path.Combine(Preconditions.CheckNonWhiteSpace(storageFolder, nameof(storageFolder)), "availability");

            try
            {
                Directory.CreateDirectory(storageDirectory);
                this.checkpointFile       = Path.Combine(storageDirectory, "avaliability.checkpoint");
                this.updateCheckpointFile = new PeriodicTask(this.UpdateCheckpointFile, this.checkpointFrequency, this.checkpointFrequency, this.log, "Checkpoint Availability");
            }
            catch (Exception ex)
            {
                this.log.LogError(ex, "Could not create checkpoint directory");
            }
        }
Exemplo n.º 36
0
        static public void TaskStart(bool once = false)
        {
            PeriodicTask Task = ScheduledActionService.Find("SimpleTasks_Task") as PeriodicTask;

            if (Task != null)
            {
                if (once)
                {
                    return;
                }
                try
                {
                    ScheduledActionService.Remove("SimpleTasks_Task");
                }
                catch (Exception)
                {
                }
            }

            Task             = new PeriodicTask("SimpleTasks_Task");
            Task.Description = "Task agent for SimpleTasks";

            try
            {
                ScheduledActionService.Add(Task);
                #if (DEBUG)
                ScheduledActionService.LaunchForTest("SimpleTasks_Task", TimeSpan.FromSeconds(30));
                #endif
            }
            catch (Exception)
            {
            }
        }
Exemplo n.º 37
0
        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            const string TASK_NAME = "GPS_TesteTask";
            var scheduleTask = ScheduledActionService.Find(TASK_NAME);
            if (scheduleTask == null)
            {
                scheduleTask = new PeriodicTask(TASK_NAME)
                {
                    Description = "Teste de GPS em background"
                };

                ScheduledActionService.Add(scheduleTask);
            }
            else if (scheduleTask.IsEnabled)
            {
                ScheduledActionService.Remove(TASK_NAME);
                ScheduledActionService.Add(scheduleTask);
            }

#if DEBUG
            ScheduledActionService.LaunchForTest(TASK_NAME, TimeSpan.FromSeconds(10));
#endif
            // inicializar o GPS uma vez na thread principal
            new GeoCoordinateWatcher(GeoPositionAccuracy.High).Start();
        }
        private void StartAddressManager()
        {
            if (!File.Exists(dataFolder.AddrManFile))
            {
                Logs.FullNode.LogInformation($"Creating {dataFolder.AddrManFile}");
                addressManager = new AddressManager();
                addressManager.SavePeerFile(dataFolder.AddrManFile, network);
                Logs.FullNode.LogInformation("Created");
            }
            else
            {
                Logs.FullNode.LogInformation($"Loading  {dataFolder.AddrManFile}");
                addressManager = AddressManager.LoadPeerFile(dataFolder.AddrManFile);
                Logs.FullNode.LogInformation("Loaded");
            }

            if (addressManager.Count == 0)
            {
                Logs.FullNode.LogInformation("AddressManager is empty, discovering peers...");
            }

            flushAddressManagerTask = new PeriodicTask("FlushAddressManager", (cancellation) =>
            {
                addressManager.SavePeerFile(dataFolder.AddrManFile, network);
            })
                                      .Start(cancellationProvider.Cancellation.Token, TimeSpan.FromMinutes(5.0), true);
        }
        public void Start()
        {
            PeriodicTask periodicTask = new PeriodicTask(Constants.SETTINGS.LIVE_TILE_AGENT);

            WP_to_WP.UI.Services.UiSettings Settings = new WP_to_WP.UI.Services.UiSettings();

            periodicTask.Description    = Settings.AppName() + " Task";
            periodicTask.ExpirationTime = System.DateTime.Now.AddDays(10);

            if (Exists())
            {
                ScheduledActionService.Remove(Constants.SETTINGS.LIVE_TILE_AGENT);
            }

            try
            {
                ScheduledActionService.Add(periodicTask);

#if DEBUG
                ScheduledActionService.LaunchForTest(Constants.SETTINGS.LIVE_TILE_AGENT, TimeSpan.FromSeconds(60));
#endif
            }
            catch (InvalidOperationException ex)
            {
                if (ex.Message.Contains("BNS Error: The action is disabled"))
                {
                    // MessageBox.Show("Background agents for this application have been disabled by the user.");
                }
            }
        }
Exemplo n.º 40
0
        public Client Start(SdjMainViewModel main)
        {
            SdjMainViewModel           = main;
            Receiver                   = new ClientReceiver(main);
            _debug                     = new Debug("Connection");
            Config                     = ClientConfig.LoadConfig();
            ClientInfo.Instance.Client = ScsClientFactory.CreateClient(new ScsTcpEndPoint(Config.Ip, Config.Port));
            ClientInfo.Instance.Client.MessageReceived += Client_MessageReceived;
            ClientInfo.Instance.Client.Disconnected    += Client_Disconnected;
            ClientInfo.Instance.ReplyMessenger          = new RequestReplyMessenger <IScsClient>(ClientInfo.Instance.Client);
            ClientInfo.Instance.ReplyMessenger.Start();

            ClientInfo.Instance.Client.ConnectTimeout = 400;

            while (ClientInfo.Instance.Client.CommunicationState == CommunicationStates.Disconnected)
            {
                try
                {
#if DEBUG
                    Thread.Sleep(1000);
#endif
                    ClientInfo.Instance.Client.Connect();
                }
                catch (TimeoutException e)
                {
                    _debug.Log(e.Message);
                }
            }

            PeriodicTask.StartNew(80, RefreshData);

            Sender = new ClientSender(ClientInfo.Instance.Client, ClientInfo.Instance.ReplyMessenger);
            return(this);
        }
Exemplo n.º 41
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            string name="PeriodicTask";
            PeriodicTask periodicTask = ScheduledActionService.Find(name) as PeriodicTask;
            if (periodicTask == null)
            {
                periodicTask = new PeriodicTask(name);
            }
            else
            {
                ScheduledActionService.Remove(name);
                periodicTask = new PeriodicTask(name);
            }
            periodicTask.Description = "描述我们的PeriodicTask后台任务是干什么的"; 
            try
            {
                ScheduledActionService.Add(periodicTask);

                ScheduledActionService.LaunchForTest(name, TimeSpan.FromSeconds(1));
            }
            catch (InvalidOperationException ioe)
            {


            }


        }
        public void PeriodicTaskBasicScenarioTest()
        {
            var cancellationTokenSource = new CancellationTokenSource();

            var counter = 0;

            var task = PeriodicTask
                       .StartNew
                       (
                () => { counter++; },
                TimeSpan.FromMilliseconds(10),
                cancellationTokenSource.Token
                       );

            task.Wait(TimeSpan.FromMilliseconds(100));

            cancellationTokenSource.Cancel();
            try
            {
                task.Wait(cancellationTokenSource.Token);
            }
            catch (OperationCanceledException)
            {
                // do nothing
            }

            Assert.IsTrue(counter > 2);
        }
Exemplo n.º 43
0
        public void startBackground()
        {
            pollOut = new PeriodicTask("ScheduledAgent");


            try
            {
                pollOut = ScheduledActionService.Find("PollOut") as PeriodicTask;
                if (pollOut != null)
                {
                    ScheduledActionService.Remove("PollOut");
                }

                pollOut             = new PeriodicTask("PollOut");
                pollOut.Description = "waiting to shut down or wake your pc";

                ScheduledActionService.Add(pollOut);

                ScheduledActionService.LaunchForTest("PollOut", TimeSpan.FromSeconds(10));
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
Exemplo n.º 44
0
        private static ILayer CreateMutatingTriangleLayer(BoundingBox envelope)
        {
            var layer = new MemoryLayer();

            var polygon = new Polygon(new LinearRing(GenerateRandomPoints(envelope, 3)));
            var feature = new Feature()
            {
                Geometry = polygon
            };
            var features = new Features();

            features.Add(feature);

            layer.DataSource = new MemoryProvider(features);

            PeriodicTask.Run(() =>
            {
                polygon.ExteriorRing = new LinearRing(GenerateRandomPoints(envelope, 3));
                // Clear cache for change to show
                feature.RenderedGeometry.Clear();
                // Trigger DataChanged notification
                layer.RefreshData(layer.Envelope, 1, true);
            },
                             TimeSpan.FromMilliseconds(1000));

            return(layer);
        }
Exemplo n.º 45
0
        private void StartPeriodicTask()
        {
            PeriodicTask periodicTask = new PeriodicTask("DatingDiaryTask");

            periodicTask.Description = "Are presenting a periodic task";

            try
            {
                ScheduledActionService.Add(periodicTask);
                ScheduledActionService.LaunchForTest("DatingDiaryTask", TimeSpan.FromSeconds(3));
                MessageBox.Show("Open the background agent success");
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("exists already"))
                {
                    MessageBox.Show("Since then the background agent success is already running");
                }
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    MessageBox.Show("Background processes for this application has been prohibited");
                }
                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    MessageBox.Show("You open the daemon has exceeded the hardware limitations");
                }
            }
            catch (SchedulerServiceException)
            {
            }
        }
Exemplo n.º 46
0
        void StartPeriodicAgent()
        {
            isEnabled = true;
            string periodicTaskName = "PeriodicAgent";

            periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
            if (periodicTask != null)
            {
                RemoveAgent(periodicTaskName);
            }

            periodicTask             = new PeriodicTask(periodicTaskName);
            periodicTask.Description = "Location Periodic Task";

            try
            {
                ScheduledActionService.Add(periodicTask);
                //MessageBox.Show("Started");
#if DEBUG_AGENT
                ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(60));
#endif
            }
            catch (InvalidOperationException exception)
            {
                //MessageBox.Show(exception.Message);
                isEnabled = false;
            }
            catch (SchedulerServiceException) { }
        }
Exemplo n.º 47
0
        /// <summary>
        /// Initializes node's address manager. Loads previously known peers from the file
        /// or creates new peer file if it does not exist. Creates periodic task to persist changes
        /// in peers to disk.
        /// </summary>
        private void StartAddressManager()
        {
            if (!File.Exists(this.dataFolder.AddrManFile))
            {
                this.logger.LogInformation($"Creating {this.dataFolder.AddrManFile}");
                this.addressManager = new AddressManager();
                this.addressManager.SavePeerFile(this.dataFolder.AddrManFile, this.network);
                this.logger.LogInformation("Created");
            }
            else
            {
                this.logger.LogInformation($"Loading  {this.dataFolder.AddrManFile}");
                this.addressManager = AddressManager.LoadPeerFile(this.dataFolder.AddrManFile);
                this.logger.LogInformation("Loaded");
            }

            if (this.addressManager.Count == 0)
            {
                this.logger.LogInformation("AddressManager is empty, discovering peers...");
            }

            this.flushAddressManagerTask = new PeriodicTask("FlushAddressManager", this.logger, (cancellation) =>
            {
                this.addressManager.SavePeerFile(this.dataFolder.AddrManFile, this.network);
            })
                                           .Start(this.nodeLifetime.ApplicationStopping, TimeSpan.FromMinutes(5.0), true);
        }
Exemplo n.º 48
0
        private static void StartPeriodicAgent()
        {
            string       periodicTaskName = "SmartGuardPeriodicAgent";
            PeriodicTask periodicTask     = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;

            if (periodicTask != null)
            {
                RemoveAgent(periodicTaskName);
            }

            periodicTask             = new PeriodicTask(periodicTaskName);
            periodicTask.Description = AppResources.SmartGuardBackgroundAgent;

            #region Try Catch Finally

            try
            {
                ScheduledActionService.Add(periodicTask);
            }

            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                }

                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                }
            }
            catch (SchedulerServiceException)
            { }
            #endregion Try Catch Finally
        }
Exemplo n.º 49
0
 private void StartPeriodicAgent(int uid)
 {
     getUserNoticeTask = ScheduledActionService. Find( periodicTaskName ) as PeriodicTask;
     if ( getUserNoticeTask != null )
     {
         RemoveAgent( periodicTaskName );
     }
     getUserNoticeTask = new PeriodicTask( periodicTaskName );
     string cookie = TakeFromCookie( Config. Cookie );
     if ( cookie. IsNullOrWhitespace( ) )
     {
         return;
     }
     else
     {
         cookie = string. Format( "{0}@{1}", cookie, uid );
     }
     getUserNoticeTask. Description = cookie;
     try
     {
         ScheduledActionService. Add( getUserNoticeTask );
         ScheduledActionService. LaunchForTest( periodicTaskName, TimeSpan. FromMinutes( 20 ) );
     }
     catch ( InvalidOperationException exception )
     {
         if ( exception. Message. Contains( "BNS Error: The action is disabled" ) )
         {
             MessageBox. Show( "Background agents for this application have been disabled by the user." );
         }
     }
 }
Exemplo n.º 50
0
        public static void StartPeriodicAgent()
        {
            // Obtain a reference to the period task, if one exists
            var periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update 
            // the schedule
            if (periodicTask != null)
            {
                RemoveAgent(periodicTaskName);
            }

            periodicTask = new PeriodicTask(periodicTaskName);

            // The description is required for periodic agents. This is the string that the user
            // will see in the background services Settings page on the device.
            periodicTask.Description = "换一下大瓷砖背面图片";

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(periodicTask);
#if DEBUG
                ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(60));
#endif

                GoogleAnalytics.EasyTracker.GetTracker().SendEvent("StartPeriodicAgent", "Result", "success", 1);
            }
            catch
            {
                UpdateTileScheduledTaskAgent.ScheduledAgent.ResetTile();
                GoogleAnalytics.EasyTracker.GetTracker().SendEvent("StartPeriodicAgent", "Result", "failure", 1);
            }
        }
Exemplo n.º 51
0
        // Exemple de code pour la conception d'une ApplicationBar localisée
        //private void BuildLocalizedApplicationBar()
        //{
        //    // Définit l'ApplicationBar de la page sur une nouvelle instance d'ApplicationBar.
        //    ApplicationBar = new ApplicationBar();

        //    // Crée un bouton et définit la valeur du texte sur la chaîne localisée issue d'AppResources.
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // Crée un nouvel élément de menu avec la chaîne localisée d'AppResources.
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}

        // Manage the reminder task
        private void StartPeriodicTask()
        {
            Debug.WriteLine("Trying to open background agent...");
            PeriodicTask periodicTask = new PeriodicTask("RemindAgent");

            periodicTask.Description = "A task reminding the user of its events";
            try
            {
                ScheduledActionService.Add(periodicTask);
                ScheduledActionService.LaunchForTest("RemindAgent", TimeSpan.FromSeconds(3));
                Debug.WriteLine("Open the background agent success");
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("exists already"))
                {
                    Debug.WriteLine("Since then the background agent success is already running");
                }
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    Debug.WriteLine("Background processes for this application has been prohibited");
                }
                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    Debug.WriteLine("You open the daemon has exceeded the hardware limitations");
                }
                else
                {
                    Debug.WriteLine("Launching the Agent failed: unknown InvalidOperationException occured.\n" + exception.Message);
                }
            }
            catch (SchedulerServiceException)
            {
            }
        }
Exemplo n.º 52
0
 private void EnsureScheduledUpdate()
 {
     this._periodicTask = ScheduledActionService.Find(this._periodicTaskName) as PeriodicTask;
     if (this._periodicTask != null)
     {
         try
         {
             ScheduledActionService.Remove(this._periodicTaskName);
         }
         catch
         {
         }
     }
     this._periodicTask                = new PeriodicTask(this._periodicTaskName);
     this._periodicTask.Description    = "VK LiveTile update agent.";
     this._periodicTask.ExpirationTime = DateTime.Now.AddDays(14.0);
     try
     {
         ScheduledActionService.Add((ScheduledAction)this._periodicTask);
     }
     catch (InvalidOperationException ex)
     {
         ex.Message.Contains("BNS Error: The action is disabled");
         ex.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added.");
     }
     catch
     {
     }
 }
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            Logger.LogInformation($"Waiting for {Settings.Current.TestStartDelay} based on TestStartDelay setting before starting.");
            await Task.Delay(Settings.Current.TestStartDelay, cancellationToken);

            this.periodicUpdate = new PeriodicTask(this.UpdateAsync, Settings.Current.TwinUpdateFrequency, Settings.Current.TwinUpdateFrequency, Logger, "TwinDesiredPropertiesUpdate");
        }
Exemplo n.º 54
0
        private void StartPeriodicAgent()
        {
            periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
            if (periodicTask != null && !periodicTask.IsEnabled)
            {
                MessageBox.Show("Background agents for this application have been disabled by the user.");
                return;
            }
            if (periodicTask != null && periodicTask.IsEnabled)
            {
                RemoveAgent(periodicTaskName);
            }
            if (!(App.Current as App).Setting.IsLiveChecked)
            {
                return;
            }

            periodicTask             = new PeriodicTask(periodicTaskName);
            periodicTask.Description = "設定画面でライブタイルの表示をランダムにした際、目標をランダム表示させます。";
            ScheduledActionService.Add(periodicTask);

#if (DEBUG)
            ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(60));
#endif
        }
Exemplo n.º 55
0
        public static void AddAgent()
        {
            PeriodicTask task = new PeriodicTask(AgentName);
            task.Description = AgentDescription;
            task.ExpirationTime = DateTime.Now.AddDays(1);

            ScheduledActionService.Add(task);
        }
        public void StartPeriodicAgent()
        {
            // Variable for tracking enabled status of background agents for this app.
            agentsAreEnabled = true;

            // Obtain a reference to the period task, if one exists
            periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;

            // If the task already exists and background agents are enabled for the
            // application, you must remove the task and then add it again to update
            // the schedule
            if (periodicTask != null)
            {
                RemoveAgent(periodicTaskName);
            }

            periodicTask = new PeriodicTask(periodicTaskName);

            // The description is required for periodic agents. This is the string that the user
            // will see in the background services Settings page on the device.
            periodicTask.Description = "This demonstrates a periodic task.";

            // Place the call to Add in a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(periodicTask);
                //PeriodicStackPanel.DataContext = periodicTask;

                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
            #if(DEBUG_AGENT)
                ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(10));
                Debug.WriteLine("Start");
            #endif
            }
            catch (InvalidOperationException exception)
            {
                if (exception.Message.Contains("BNS Error: The action is disabled"))
                {
                    //MessageBox.Show("Background agents for this application have been disabled by the user.");
                    agentsAreEnabled = false;
                    //PeriodicCheckBox.IsChecked = false;
                }

                if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                {
                    // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached.

                }
                //PeriodicCheckBox.IsChecked = false;
            }
            catch (SchedulerServiceException)
            {
                // No user action required.
               // PeriodicCheckBox.IsChecked = false;
            }
        }
Exemplo n.º 57
0
        public ClientController()
        {
            State = ClientControllerState.Start;

              this.client = new Client();

              this.task = new PeriodicTask(null, Work, null, null);
              this.task.Delay = 1;
              this.task.Start();
        }
Exemplo n.º 58
0
        private static void RunConnectionCheckTask()
        {
            PeriodicTask periodicTask = new PeriodicTask(
                RepositoryCleaner.CheckClientsConnection,
                TimeSpan.FromSeconds(5),
                TimeSpan.FromSeconds(30),
                CancellationToken.None);

            periodicTask.DoPeriodicWorkAsync();
        }
Exemplo n.º 59
0
 public static PeriodicTask StartPeriodicTask()
 {
     if (ScheduledActionService.Find(PERIODICTASK_NAME) != null)
     {
         ScheduledActionService.Remove(PERIODICTASK_NAME);
     }
     var tskPeriodic = new PeriodicTask(PERIODICTASK_NAME);
     tskPeriodic.Description = "GPS Tracker";
     return tskPeriodic;
 }
Exemplo n.º 60
0
        public void SetTask(PeriodicTask task, double startTime, double endTime)
        {
            _task = task;
            _startTime = startTime;
            _endTime = endTime;

            _listReleaseTime = _task.GetReleaseTime(_startTime, _endTime);
            _listSoftDeadline = _task.GetSoftDeadline(_startTime, _endTime);
            _listHardDeadline = _task.GetHardDeadline(_startTime, _endTime);
        }