Ejemplo n.º 1
0
        private OneOffSchedule(
            [CanBeNull] string name,
            DateTime dateTime,
            [NotNull] string timeZone,
            ScheduleOptions options = ScheduleOptions.None)
        {
            if (timeZone == null)
            {
                throw new ArgumentNullException("timeZone");
            }

            DateTimeZone tz = TimeHelpers.DateTimeZoneProvider[timeZone];

            if (tz == null)
            {
                throw new ArgumentException(
                          // ReSharper disable once AssignNullToNotNullAttribute
                          string.Format(Resource.OneOffSchedule_InvalidTimeZone, timeZone),
                          "timeZone");
            }

            _name    = name;
            Instant  = tz.AtLeniently(LocalDateTime.FromDateTime(dateTime)).ToInstant();
            _options = options;
        }
        public async Task <EdgeDefinition> RunAsync()
        {
            var scheduleId = (long)this.Batch.Items.First().Parameters["Batch"];

            using (var context = this.dataAccess.GetContext())
            {
                this.Options = await context.NoTracking <DAL.Entities.Schedule>()
                               .Where(s => s.Id == scheduleId)
                               .Select(s => new ScheduleOptions
                {
                    IsDefault  = s.IsDefault,
                    ScheduleId = s.Id,
                    Type       = s.Type,
                    UpdateIntervalInMinutes = s.UpdateIntervalInMinutes
                })
                               .SingleOrDefaultAsync();

                switch (this.Options?.Type)
                {
                case DAL.Entities.ExecutionType.GetNewResults:
                    return(this.GetNewResults);

                case DAL.Entities.ExecutionType.UpdateOpenResults:
                    return(this.UpdateOpenResults);

                case DAL.Entities.ExecutionType.UpdateOutdatedResults:
                    return(this.UpdateOutdatedResults);

                default:
                    return(this.ScheduleNotFound);
                }
            }
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PeriodicSchedule" /> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="month">The month.</param>
 /// <param name="week">The week.</param>
 /// <param name="day">The day.</param>
 /// <param name="weekDay">The week day.</param>
 /// <param name="hour">The hour.</param>
 /// <param name="minute">The minute.</param>
 /// <param name="second">The second.</param>
 /// <param name="minimumGap">The minimum gap.</param>
 /// <param name="calendar">The calendar.</param>
 /// <param name="timeZone">The time zone.</param>
 /// <param name="options">The options.</param>
 public PeriodicSchedule(
     [CanBeNull] string name,
     Month month         = Month.Every,
     Week week           = Week.Every,
     Day day             = Day.Every,
     WeekDay weekDay     = WeekDay.Every,
     Hour hour           = Hour.Zeroth,
     Minute minute       = Minute.Zeroth,
     Second second       = Second.Zeroth,
     Duration minimumGap = default(Duration),
     [CanBeNull] CalendarSystem calendar = null,
     [CanBeNull] DateTimeZone timeZone   = null,
     ScheduleOptions options             = ScheduleOptions.None)
     : this(
         month,
         week,
         day,
         weekDay,
         hour,
         minute,
         second,
         minimumGap < Duration.Zero ? Duration.Zero : minimumGap,
         // ReSharper disable AssignNullToNotNullAttribute
         calendar ?? CalendarSystem.Iso,
         timeZone ?? DateTimeZone.Utc,
         // ReSharper restore AssignNullToNotNullAttribute
         options,
         name)
 {
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GapSchedule"/> class.
        /// </summary>
        /// <param name="timeSpan">The time span.</param>
        /// <param name="options">The options.</param>
        public GapSchedule(TimeSpan timeSpan, ScheduleOptions options = ScheduleOptions.None)
        {
            Duration duration = Duration.FromTimeSpan(timeSpan);

            Duration = duration < Duration.Zero ? Duration.Zero : duration;
            _options = options;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GapSchedule"/> class.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="timeSpan">The time span.</param>
        /// <param name="options">The options.</param>
        public GapSchedule([CanBeNull] string name, TimeSpan timeSpan, ScheduleOptions options = ScheduleOptions.None)
        {
            Duration duration = Duration.FromTimeSpan(timeSpan);

            _name    = name;
            Duration = duration < Duration.Zero ? Duration.Zero : duration;
            _options = options;
        }
Ejemplo n.º 6
0
 private OneOffSchedule(
     [CanBeNull] string name,
     DateTimeOffset dateTime,
     ScheduleOptions options = ScheduleOptions.None)
 {
     _name    = name;
     Instant  = Instant.FromDateTimeOffset(dateTime);
     _options = options;
 }
Ejemplo n.º 7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OneOffSchedule" /> class.
 /// </summary>
 /// <param name="name">An optional name for the schedule.</param>
 /// <param name="zonedDateTime">The date and time.</param>
 /// <param name="options">The options.</param>
 public OneOffSchedule(
     [CanBeNull] string name,
     ZonedDateTime zonedDateTime,
     ScheduleOptions options = ScheduleOptions.None)
 {
     _name    = name;
     Instant  = zonedDateTime.ToInstant();
     _options = options;
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FunctionalSchedule" /> class.
        /// </summary>
        /// <param name="function">The function.</param>
        /// <param name="options">The options.</param>
        public FunctionalSchedule(
            [NotNull] Func <Instant, Instant> function,
            ScheduleOptions options = ScheduleOptions.None)
        {
            if (function == null)
            {
                throw new ArgumentNullException("function");
            }

            _function = function;
            _options  = options;
        }
Ejemplo n.º 9
0
 private PeriodicSchedule(
     Month month,
     Week week,
     Day day,
     WeekDay weekDay,
     Hour hour,
     Minute minute,
     Second second,
     Duration minimumGap,
     [NotNull] CalendarSystem calendarSystem,
     [NotNull] DateTimeZone dateTimeZone,
     ScheduleOptions options,
     [CanBeNull] string name)
     : base(
         name,
         CreateFunction(
             month,
             week,
             day,
             weekDay,
             hour,
             minute,
             second,
             minimumGap,
             calendarSystem,
             dateTimeZone),
         options)
 {
     if (calendarSystem == null)
     {
         throw new ArgumentNullException("calendarSystem");
     }
     if (dateTimeZone == null)
     {
         throw new ArgumentNullException("dateTimeZone");
     }
     Month          = month;
     Week           = week;
     Day            = day;
     WeekDay        = weekDay;
     Hour           = hour;
     Minute         = minute;
     Second         = second;
     MinimumGap     = minimumGap;
     CalendarSystem = calendarSystem;
     DateTimeZone   = dateTimeZone;
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AggregateSchedule" /> class.
        /// </summary>
        /// <param name="name">An optional name for the schedule.</param>
        /// <param name="schedules">A collection of schedules.</param>
        /// <exception cref="System.ArgumentException">The specified schedules have differing options.</exception>
        public AggregateSchedule([CanBeNull] string name, [NotNull] params ISchedule[] schedules)
        {
            if (schedules == null)
            {
                throw new ArgumentNullException("schedules");
            }

            // Duplicate collection
            _schedules = schedules.Where(s => s != null).ToArray();
            _name      = name;
            if (!_schedules.Any())
            {
                _options = ScheduleOptions.None;
                return;
            }

            unchecked
            {
                int hashCode = _schedules.Length;

                // Calculate options and ensure all are identical.
                bool first = true;
                foreach (ISchedule schedule in _schedules.OrderBy(s => s.Name))
                {
                    Debug.Assert(schedule != null);

                    hashCode = (hashCode * 397) ^ schedule.GetHashCode();

                    if (first)
                    {
                        _options = schedule.Options;
                        first    = false;
                        continue;
                    }

                    if (schedule.Options != _options)
                    {
                        throw new ArgumentException(Resource.AggregateSchedule_Different_Options, "schedules");
                    }
                }

                hashCode  = (hashCode * 397) ^ (_name != null ? _name.GetHashCode() : 0);
                hashCode  = (hashCode * 397) ^ (int)_options;
                _hashCode = hashCode;
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Specifies that the configured job will be triggered by an item inserted to the a queue.
        /// </summary>
        /// <typeparam name="TState">The type of the persisted job state. This is a DTO to share state between every execution</typeparam>
        /// <param name="builder">The <see cref="TaskTriggerBuilder"/> used to configure the way that a job is triggered.</param>
        /// <param name="cronExpression">Cron expression</param>
        /// <param name="configureAction">The delegate used to configure the queue options.</param>
        /// <returns>The <see cref="WorkerHostBuilder"/> used to configure the worker host.</returns>
        public static WorkerHostBuilder WithScheduleTrigger <TState>(this TaskTriggerBuilder builder, string cronExpression, Action <ScheduleOptions> configureAction = null) where TState : class
        {
            if (string.IsNullOrWhiteSpace(cronExpression))
            {
                throw new ArgumentException($"'{nameof(cronExpression)}' cannot be null or whitespace", nameof(cronExpression));
            }
            var options = new ScheduleOptions(builder.Services)
            {
                CronExpression = cronExpression
            };

            configureAction?.Invoke(options);
            options.Services.AddTransient(builder.JobHandlerType);
            options.Services.AddTransient(typeof(IScheduledTaskStore <TState>), builder.Options.ScheduledTaskStoreType.MakeGenericType(typeof(TState)));
            options.Services.AddTransient(typeof(ScheduledJob <,>).MakeGenericType(builder.JobHandlerType, typeof(TState)));
            options.Services.AddTransient(serviceProvider => new ScheduledJobSettings(builder.JobHandlerType, typeof(TState), cronExpression, options.Name, options.Group, options.Description));
            return(new WorkerHostBuilder(options.Services, builder.Options));
        }
Ejemplo n.º 12
0
        public async static Task Run()
        {
            // =========================================================
            // Iron.io Worker
            // =========================================================

            Console.WriteLine("Be sure to create a 'Test' worker before running this sample");
            Console.WriteLine("Press ANY key to continue");
            Console.Read();

            IronWorkerRestClient workerClient = Client.New();

            string taskId = await workerClient.Tasks.Create("Test", new { Key = "Value" });

            Console.WriteLine("TaskID: {0}", taskId);

            TaskInfoCollection taskInfoCollection = await workerClient.Tasks.List("Test");

            foreach (TaskInfo task in taskInfoCollection.Tasks)
            {
                Console.WriteLine(task.Inspect());
            }

            ScheduleOptions options = ScheduleBuilder.Build().
                                      Delay(TimeSpan.FromMinutes(1)).
                                      WithFrequency(TimeSpan.FromHours(1)).
                                      RunFor(TimeSpan.FromHours(3)).
                                      WithPriority(TaskPriority.Default);

            var payload = new
            {
                a = "b",
                c = new[] { 1, 2, 3 }
            };

            ScheduleIdCollection schedule = await workerClient.Schedules.Create("Test", payload, options);

            Console.WriteLine(schedule.Inspect());

            await workerClient.Schedules.Cancel(schedule.Schedules.First().Id);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Starts the machinery
        /// </summary>
        void LoadConfiguration()
        {
            ScheduleOptions options = null;

            // fixed bug with restoring from sleep mode(do not access disk drive)
            try
            {
                options = ScheduleOptionsManager.Load();
                ScheduleOptionsManager.Validate(options);
            }
            catch (FileNotFoundException)
            {
                // but no config was created
                // it's normal situation after installation
                // so we're exiting
                Environment.Exit(0);
            }
            catch (ScheduleOptionsInvalidException)
            {
                seriousBugHelper(_InvalidOptions, true);
            }
            catch (Exception e)
            {
                ImproveIt.ProcessUnhandledException(e);
            }

            // if there's no scheduling
            if (!options.EnableScheduling)
            {
                // we're exiting to free system resources
                Environment.Exit(0);
            }
            else
            {
                _scheduler.Options = options;
                Resume();
            }
        }
Ejemplo n.º 14
0
        private void EditTaskOptions()
        {
            if(activeTask != null) {
                ScheduledTask task = (ScheduledTask)activeTask.Tag;
                ScheduleOptions options = new ScheduleOptions();
                options.Options = _options;
                options.EditMode = true;
                options.Task = task;

                if(options.ShowDialog() == DialogResult.OK) {
                    ListViewItem taskItem = null;
                    ScheduledTask newTask = options.Task;

                    for(int i = 0; i < TaskList.Items.Count; i++) {
                        if((ScheduledTask)TaskList.Items[i].Tag == (ScheduledTask)activeTask.Tag) {
                            taskItem = TaskList.Items[i];
                            break;
                        }
                    }

                    TaskManager.SaveTask(SecureDeleteLocations.GetTaskFile(task.TaskId), newTask);

                    // update the <guid,taskName> mapping
                    if(_options.SessionNames.ContainsKey(newTask.TaskId)) {
                        _options.SessionNames[task.TaskId] = newTask.Name;
                    }
                    else {
                        _options.SessionNames.Add(task.TaskId, newTask.Name);
                    }

                    // save options
                    SDOptionsFile.TrySaveOptions(_options);
                    manager.LoadOptions();

                    // reschedule
                    disableRescheduling = true;

                    if(manager.LoadAndHandleTask(newTask.TaskId) == false) {
                        Debug.ReportWarning("Failed to handle edited task");
                    }
                    else {
                        // update interface
                        if(taskItem != null) {
                            taskItem.Tag = manager.GetTaskById(task.TaskId);
                            activeTask = taskItem;
                        }

                        UpdateTaskItem(activeTask);
                    }
                    disableRescheduling = false;
                }
            }
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GapSchedule"/> class.
 /// </summary>
 /// <param name="duration">The duration.</param>
 /// <param name="options">The options.</param>
 public GapSchedule(Duration duration, ScheduleOptions options = ScheduleOptions.None)
 {
     Duration = duration < Duration.Zero ? Duration.Zero : duration;
     _options = options;
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GapSchedule"/> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="duration">The duration.</param>
 /// <param name="options">The options.</param>
 public GapSchedule([CanBeNull] string name, Duration duration, ScheduleOptions options = ScheduleOptions.None)
 {
     _name    = name;
     Duration = duration < Duration.Zero ? Duration.Zero : duration;
     _options = options;
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OneOffSchedule" /> class.
 /// </summary>
 /// <param name="name">An optional name for the schedule.</param>
 /// <param name="instant">The instant.</param>
 /// <param name="options">The options.</param>
 public OneOffSchedule([CanBeNull] string name, Instant instant, ScheduleOptions options = ScheduleOptions.None)
 {
     _name    = name;
     Instant  = instant;
     _options = options;
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OneOffSchedule" /> class.
 /// </summary>
 /// <param name="instant">The instant.</param>
 /// <param name="options">The options.</param>
 public OneOffSchedule(Instant instant, ScheduleOptions options = ScheduleOptions.None)
 {
     Instant  = instant;
     _options = options;
 }
Ejemplo n.º 19
0
 public ScheduleResult[] Schedule(ScheduleOptions Options, string Action, [System.Xml.Serialization.XmlElementAttribute("Schedule")] ScheduleDefinition Schedule1, [System.Xml.Serialization.XmlArrayItemAttribute("Interaction", IsNullable=false)] APIObject[] Interactions, out string OverallStatus, out string OverallStatusMessage, out string RequestID) {
     object[] results = this.Invoke("Schedule", new object[] {
                 Options,
                 Action,
                 Schedule1,
                 Interactions});
     OverallStatus = ((string)(results[1]));
     OverallStatusMessage = ((string)(results[2]));
     RequestID = ((string)(results[3]));
     return ((ScheduleResult[])(results[0]));
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OneOffSchedule" /> class.
 /// </summary>
 /// <param name="zonedDateTime">The date and time.</param>
 /// <param name="options">The options.</param>
 public OneOffSchedule(ZonedDateTime zonedDateTime, ScheduleOptions options = ScheduleOptions.None)
 {
     Instant  = zonedDateTime.ToInstant();
     _options = options;
 }
Ejemplo n.º 21
0
        private void AddTask()
        {
            WipeSession session = new WipeSession();
            session.GenerateGuid();
            ScheduledTask task = new ScheduledTask();
            task.TaskId = session.SessionId;
            task.Schedule = new OneTimeSchedule();
            task.Name = "Untitled task";
            task.Enabled = true;

            // show the dialog
            ScheduleOptions options = new ScheduleOptions();
            options.Options = _options;
            options.EditMode = false;
            options.Task = task;

            if(options.ShowDialog() == DialogResult.OK) {
                task = options.Task;
                manager.LoadOptions();
                manager.AddTask(task, true);

                SessionSaver.SaveSession(session, SecureDeleteLocations.GetSessionFile(task.TaskId));
                ListViewItem item = CreateTaskItem(task);
                UpdateTaskItem(item);

                // add to the <guid,taskName> mapping
                _options.SessionNames.Add(task.TaskId, task.Name);
                SDOptionsFile.TrySaveOptions(_options);
                TaskList.Items[TaskList.Items.Count - 1].Selected = true;
            }

            _actionManager.StateChanged();
        }
Ejemplo n.º 22
0
        private static void Main(string[] args)
        {
            LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter();

            // =========================================================
            // Iron.io MQ
            // =========================================================

            //IronMqRestClient ironMq = IronSharp.IronMQ.Client.New();

            // For beta testing
            IronMqRestClient ironMq = IronSharp.IronMQ.Client.New(new IronClientConfig {
                ProjectId = "53a3b3bd5e8edd1245000005", Token = "O7KrMTwmw997iq0KzL7v", Host = "192.168.1.155", ApiVersion = 3, Port = 8080, Scheme = Uri.UriSchemeHttp
            });

            // Simple actions

            // Post message to a queue
            TestPosting(ironMq);

            // Post message to a queue and reserve it
            TestReservation(ironMq);

            // Post message, reserve it and delete
            TestDeletingReservedMessage(ironMq);

            // Actions on queue

            // Update queue info
            TestUpdatingTheQueue(ironMq);

            // Clear all messages of queue
            TestClearingQueue(ironMq);

            // Delete queue and its messages
            TestDeletingQueue(ironMq);

            // Get list of all queus inside project
            TestGettingListQueue(ironMq);

            // Actions on messages

            //TestPosting(ironMq);
            //TestReservation(ironMq);
            //TestDeletingReservedMessage(ironMq);

            // Get message by id without reservation
            TestGettingMessageById(ironMq);

            // Get message without reserving it
            TestPeekingMessage(ironMq);

            // Delete unreserved message
            TestDeletingMessage(ironMq);

            // Touch message to prolongate reservation
            TestTouching(ironMq);

            // Touch message to prolongate reservation
            TestTouchingTwice(ironMq);

            // Release reserved message
            TestReleasing(ironMq);

            // Delete a bunch of messages
            TestDeletingMessages(ironMq);

            // Get subscriber's URL
            TestGettingSubscribersInfo(ironMq);

            // =========================================================
            // Iron.io Worker
            // =========================================================

            Console.WriteLine("Be sure to create a 'Test' worker before running this sample");
            Console.WriteLine("Press ANY key to continue");
            Console.Read();

            IronWorkerRestClient workerClient = IronSharp.IronWorker.Client.New();

            string taskId = workerClient.Tasks.Create("Test", new { Key = "Value" });

            Console.WriteLine("TaskID: {0}", taskId);

            TaskInfoCollection taskInfoCollection = workerClient.Tasks.List("Test");

            foreach (TaskInfo task in taskInfoCollection.Tasks)
            {
                Console.WriteLine(task.Inspect());
            }

            ScheduleOptions options = ScheduleBuilder.Build().
                                      Delay(TimeSpan.FromMinutes(1)).
                                      WithFrequency(TimeSpan.FromHours(1)).
                                      RunFor(TimeSpan.FromHours(3)).
                                      WithPriority(TaskPriority.Default);

            var payload = new
            {
                a = "b",
                c = new[] { 1, 2, 3 }
            };

            ScheduleIdCollection schedule = workerClient.Schedules.Create("Test", payload, options);

            Console.WriteLine(schedule.Inspect());

            workerClient.Schedules.Cancel(schedule.Schedules.First().Id);

            // =========================================================
            // Iron.io Cache
            // =========================================================

            IronCacheRestClient ironCacheClient = IronSharp.IronCache.Client.New();

            // Get a Cache object
            CacheClient cache = ironCacheClient.Cache("my_cache");

            // Put value to cache by key
            cache.Put("number_item", 42);

            // Get value from cache by key
            Console.WriteLine(cache.Get("number_item").Value);

            // Get value from cache by key
            Console.WriteLine(cache.Get <int>("number_item"));

            // Numbers can be incremented
            cache.Increment("number_item", 10);

            // Immediately delete an item
            cache.Delete("number_item");

            cache.Put("complex_item", new { greeting = "Hello", target = "world" });

            // Get value from cache by key
            Console.WriteLine(cache.Get("complex_item").Value);

            cache.Delete("complex_item");

            Console.WriteLine("============= Done ==============");
            Console.Read();
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Schedule Constructor. Constructed from [options]
 /// </summary>
 /// <param name="options"></param>
 public Schedule(ScheduleOptions options)
     : this(options.StartDate, options.Version)
 {    /**/
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Recalculates the next due date.
        /// </summary>
        /// <param name="due">The instant the schedule was last due to run, or completed.</param>
        internal void RecalculateNextDue(Instant due)
        {
            // Increment recalculate counter, only let first increment continue.
            if (Interlocked.Increment(ref _calculatorCount) > 1)
            {
                return;
            }

            do
            {
                try
                {
                    long    ndt = Interlocked.Read(ref NextDueTicksInternal);
                    Instant now = TimeHelpers.Clock.Now;
                    long    nt  = now.Ticks;

                    // If next due is in future, ask schedule when we're next due.
                    if (ndt > nt)
                    {
                        ScheduleOptions options = Schedule.Options;
                        Instant         last;
                        if (!options.HasFlag(ScheduleOptions.FromDue))
                        {
                            Instant lef = LastExecutionFinished;
                            last = lef > Instant.MinValue
                                ? lef
                                : TimeHelpers.Clock.Now;
                        }
                        else
                        {
                            last = due > Instant.MinValue
                                ? due
                                : TimeHelpers.Clock.Now;
                        }

                        ndt = Schedule.Next(last).Ticks;

                        // If options >= 4 means one of the alignment flags is set.
                        if ((byte)options >= 4)
                        {
                            // Align the ticks as per flags.
                            if (options.HasFlag(ScheduleOptions.AlignHours))
                            {
                                ndt = ((ndt + NodaConstants.TicksPerHour - 1) / NodaConstants.TicksPerHour) *
                                      NodaConstants.TicksPerHour;
                            }
                            else if (options.HasFlag(ScheduleOptions.AlignMinutes))
                            {
                                ndt = ((ndt + NodaConstants.TicksPerMinute - 1) / NodaConstants.TicksPerMinute) *
                                      NodaConstants.TicksPerMinute;
                            }
                            else if (options.HasFlag(ScheduleOptions.AlignSeconds))
                            {
                                ndt = ((ndt + NodaConstants.TicksPerSecond - 1) / NodaConstants.TicksPerSecond) *
                                      NodaConstants.TicksPerSecond;
                            }
                        }
                    }

                    // If it's more than the max clamp to max.
                    if (ndt > Scheduler.MaxTicks)
                    {
                        ndt = Scheduler.MaxTicks;
                    }

                    // Update next due
                    Interlocked.Exchange(ref NextDueTicksInternal, ndt);
                }
                finally
                {
                    // Mark update as done.
                    Interlocked.Decrement(ref _calculatorCount);
                }

                // Keep going if we need to recalculate.
            } while (_calculatorCount < 0);

            // Notify the scheduler that we've changed our due date.
            Scheduler.CheckSchedule();
        }
Ejemplo n.º 25
0
 /// <remarks/>
 public void ScheduleAsync(ScheduleOptions Options, string Action, ScheduleDefinition Schedule1, APIObject[] Interactions) {
     this.ScheduleAsync(Options, Action, Schedule1, Interactions, null);
 }
Ejemplo n.º 26
0
        private static void Main(string[] args)
        {
            LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter();
            IronMqRestClient ironMq = IronSharp.IronMQ.Client.New(new IronClientConfig {
                ProjectId = "5bf768af967e0f000910fed3", Token = "y7TU7c3D3IUXtwrcJJFH", Host = "mq-aws-eu-west-1-1.iron.io", ApiVersion = 3, Scheme = Uri.UriSchemeHttp
            });

            QueueClient queueHabitacion  = ironMq.Queue("Habitacion");
            var         codigoHabitacion = "HBT0000007";
            string      messageId1       = queueHabitacion.Post(codigoHabitacion);

            Console.WriteLine("Mensaje enviado: {0}", codigoHabitacion);

            QueueClient queueHotel  = ironMq.Queue("Hotel");
            var         codigoHotel = "HT00000002";
            string      messageId2  = queueHotel.Post(codigoHotel);

            Console.WriteLine("Mensaje enviado: {0}", codigoHabitacion);

            //QueueMessage messageHabitacion = queueHabitacion.Reserve();
            //Console.WriteLine("Respuesta: " + messageHabitacion.Body);

            //QueueMessage messageHotel = queueHotel.Reserve();
            //Console.WriteLine("Respuesta: " + messageHotel.Body);
            //Console.WriteLine(message.ReservationId);


            //bool finished = false;
            //var hotelIds = new List<string>();
            //while (!finished)
            //{
            //    messageHotel = queueHotel.Reserve();
            //    if (messageHotel != null)
            //        hotelIds.Add(messageHotel.Body);
            //    else
            //        finished = true;
            //}



            LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter();

            // =========================================================
            // Iron.io MQ
            // =========================================================

            //IronMqRestClient ironMq = IronSharp.IronMQ.Client.New();

            // For beta testing
            //IronMqRestClient ironMq = IronSharp.IronMQ.Client.New(new IronClientConfig { ProjectId = "53a3b3bd5e8edd1245000005", Token = "O7KrMTwmw997iq0KzL7v", Host = "192.168.1.155", ApiVersion = 3, Port = 8080, Scheme = Uri.UriSchemeHttp });

            // Simple actions

            // Post message to a queue
            TestPosting(ironMq);

            // Post message to a queue and reserve it
            TestReservation(ironMq);

            // Post message, reserve it and delete
            TestDeletingReservedMessage(ironMq);

            // Actions on queue

            // Update queue info
            TestUpdatingTheQueue(ironMq);

            // Clear all messages of queue
            TestClearingQueue(ironMq);

            // Delete queue and its messages
            TestDeletingQueue(ironMq);

            // Get list of all queus inside project
            TestGettingListQueue(ironMq);

            // Actions on messages

            //TestPosting(ironMq);
            //TestReservation(ironMq);
            //TestDeletingReservedMessage(ironMq);

            // Get message by id without reservation
            TestGettingMessageById(ironMq);

            // Get message without reserving it
            TestPeekingMessage(ironMq);

            // Delete unreserved message
            TestDeletingMessage(ironMq);

            // Touch message to prolongate reservation
            TestTouching(ironMq);

            // Touch message to prolongate reservation
            TestTouchingTwice(ironMq);

            // Release reserved message
            TestReleasing(ironMq);

            // Delete a bunch of messages
            TestDeletingMessages(ironMq);

            // Get subscriber's URL
            TestGettingSubscribersInfo(ironMq);

            // =========================================================
            // Iron.io Worker
            // =========================================================

            Console.WriteLine("Be sure to create a 'Test' worker before running this sample");
            Console.WriteLine("Press ANY key to continue");
            Console.Read();

            IronWorkerRestClient workerClient = IronSharp.IronWorker.Client.New();

            string taskId = workerClient.Tasks.Create("Test", new { Key = "Value" });

            Console.WriteLine("TaskID: {0}", taskId);

            TaskInfoCollection taskInfoCollection = workerClient.Tasks.List("Test");

            foreach (TaskInfo task in taskInfoCollection.Tasks)
            {
                Console.WriteLine(task.Inspect());
            }

            ScheduleOptions options = ScheduleBuilder.Build().
                                      Delay(TimeSpan.FromMinutes(1)).
                                      WithFrequency(TimeSpan.FromHours(1)).
                                      RunFor(TimeSpan.FromHours(3)).
                                      WithPriority(TaskPriority.Default);

            var payload = new
            {
                a = "b",
                c = new[] { 1, 2, 3 }
            };

            ScheduleIdCollection schedule = workerClient.Schedules.Create("Test", payload, options);

            Console.WriteLine(schedule.Inspect());

            workerClient.Schedules.Cancel(schedule.Schedules.First().Id);

            // =========================================================
            // Iron.io Cache
            // =========================================================

            IronCacheRestClient ironCacheClient = IronSharp.IronCache.Client.New();

            // Get a Cache object
            CacheClient cache = ironCacheClient.Cache("my_cache");

            // Put value to cache by key
            cache.Put("number_item", 42);

            // Get value from cache by key
            Console.WriteLine(cache.Get("number_item").Value);

            // Get value from cache by key
            Console.WriteLine(cache.Get <int>("number_item"));

            // Numbers can be incremented
            cache.Increment("number_item", 10);

            // Immediately delete an item
            cache.Delete("number_item");

            cache.Put("complex_item", new { greeting = "Hello", target = "world" });

            // Get value from cache by key
            Console.WriteLine(cache.Get("complex_item").Value);

            cache.Delete("complex_item");

            Console.WriteLine("============= Done ==============");
            Console.Read();
        }
Ejemplo n.º 27
0
 /// <remarks/>
 public void ScheduleAsync(ScheduleOptions Options, string Action, ScheduleDefinition Schedule1, APIObject[] Interactions, object userState) {
     if ((this.ScheduleOperationCompleted == null)) {
         this.ScheduleOperationCompleted = new System.Threading.SendOrPostCallback(this.OnScheduleOperationCompleted);
     }
     this.InvokeAsync("Schedule", new object[] {
                 Options,
                 Action,
                 Schedule1,
                 Interactions}, this.ScheduleOperationCompleted, userState);
 }