public JobList <DeletedJobDto> DeletedJobs(int @from, int count)
 {
     return(UseConnection(connection => GetJobs(
                              connection,
                              from,
                              count,
                              DeletedState.StateName,
                              (sqlJob, job, stateData) => new DeletedJobDto
     {
         Job = job,
         DeletedAt = JobHelper.DeserializeNullableDateTime(stateData["DeletedAt"])
     })));
 }
Exemple #2
0
 public JobList <SucceededJobDto> SucceededJobs(int from, int count)
 {
     return(UseConnection(connection => GetJobs(connection, from, count, SucceededState.StateName,
                                                (sqlJob, job, stateData) => new SucceededJobDto
     {
         Job = job,
         Result = stateData.ContainsKey("Result") ? stateData["Result"] : null,
         TotalDuration = stateData.ContainsKey("PerformanceDuration") && stateData.ContainsKey("Latency")
                 ? (long?)long.Parse(stateData["PerformanceDuration"]) + (long?)long.Parse(stateData["Latency"])
                 : null,
         SucceededAt = JobHelper.DeserializeNullableDateTime(stateData["SucceededAt"])
     })));
 }
Exemple #3
0
 public JobList <FailedJobDto> FailedJobs(int from, int count)
 {
     return(UseConnection(connection => GetJobs(connection, from, count, FailedState.StateName,
                                                (sqlJob, job, stateData) => new FailedJobDto
     {
         Job = job,
         Reason = sqlJob.StateReason,
         ExceptionDetails = stateData["ExceptionDetails"],
         ExceptionMessage = stateData["ExceptionMessage"],
         ExceptionType = stateData["ExceptionType"],
         FailedAt = JobHelper.DeserializeNullableDateTime(stateData["FailedAt"])
     })));
 }
 public JobList <DeletedJobDto> DeletedJobs(int from, int count)
 {
     return(_storage.UseStatelessTransaction(session => GetJobs(
                                                 session,
                                                 @from,
                                                 count,
                                                 DeletedState.StateName,
                                                 (sqlJob, job, stateData) => new DeletedJobDto
     {
         Job = job,
         DeletedAt = JobHelper.DeserializeNullableDateTime(stateData["DeletedAt"])
     })));
 }
        public JobList <FailedJobDto> FailedJobs(int from, int count)
        {
            List <KeyValuePair <string, FailedJobDto> > result = GetJobsOnState(States.FailedState.StateName, from, count, (state, job) => new FailedJobDto
            {
                Job              = job,
                Reason           = state.Reason,
                FailedAt         = JobHelper.DeserializeNullableDateTime(state.Data["FailedAt"]),
                ExceptionDetails = state.Data["ExceptionDetails"],
                ExceptionMessage = state.Data["ExceptionMessage"],
                ExceptionType    = state.Data["ExceptionType"],
            }).OrderByDescending(j => j.Value.FailedAt).ToList();

            return(new JobList <FailedJobDto>(result));
        }
 public JobList <DeletedJobDto> DeletedJobs(int @from, int count)
 {
     return(UseConnection(connection => GetJobs(
                              connection,
                              from,
                              count,
                              DeletedState.StateName,
                              (sqlJob, job, stateData) => new DeletedJobDto
     {
         Job = job,
         InDeletedState = DeletedState.StateName.Equals(sqlJob.StateName, StringComparison.OrdinalIgnoreCase),
         DeletedAt = JobHelper.DeserializeNullableDateTime(stateData["DeletedAt"])
     })));
 }
Exemple #7
0
 public JobList <FailedJobDto> FailedJobs(int from, int count)
 {
     return(GetJobs(from, count, FailedState.StateName,
                    (job, data, reason) => new FailedJobDto
     {
         Job = job,
         Reason = reason,
         ExceptionDetails = data?.GetValue(nameof(FailedJobDto.ExceptionDetails)),
         ExceptionMessage = data?.GetValue(nameof(FailedJobDto.ExceptionMessage)),
         ExceptionType = data?.GetValue(nameof(FailedJobDto.ExceptionType)),
         FailedAt = JobHelper.DeserializeNullableDateTime(
             data?.GetValue(nameof(FailedJobDto.FailedAt))),
     }));
 }
 public JobList <DeletedJobDto> DeletedJobs(int @from, int count)
 {
     return(GetJobs(
                from,
                count,
                DeletedState.StateName,
                (sqlJob, job, stateData) => new DeletedJobDto
     {
         Job = job,
         DeletedAt = JobHelper.DeserializeNullableDateTime(stateData.ContainsKey("DeletedAt")
                 ? stateData["DeletedAt"]
                 : null)
     }));
 }
 public JobList <ProcessingJobDto> ProcessingJobs(int @from, int count)
 {
     return(UseConnection(connection => GetJobs(
                              connection,
                              from, count,
                              ProcessingState.StateName,
                              (sqlJob, job, stateData) => new ProcessingJobDto
     {
         Job = job,
         InProcessingState = ProcessingState.StateName.Equals(sqlJob.StateName, StringComparison.OrdinalIgnoreCase),
         ServerId = stateData.ContainsKey("ServerId") ? stateData["ServerId"] : stateData["ServerName"],
         StartedAt = JobHelper.DeserializeNullableDateTime(stateData["StartedAt"]),
     })));
 }
        /// <summary>
        /// 获取队列列表
        /// </summary>
        public IList <QueueWithTopEnqueuedJobsDto> Queues() =>
        UseConnection(redis =>
        {
            var queues = redis.SMembers(_storage.GetRedisKey("queues"));

            var result = new List <QueueWithTopEnqueuedJobsDto>(queues.Length);

            foreach (var queue in queues)
            {
                string[] firstJobIds = null;
                long length          = 0;
                long fetched         = 0;


                Task[] tasks = new Task[3];
                tasks[0]     = _redisClient.LRangeAsync(
                    _storage.GetRedisKey($"queue:{queue}"), -5, -1)
                               .ContinueWith(x => firstJobIds = x.Result);

                tasks[1] = _redisClient.LLenAsync(_storage.GetRedisKey($"queue:{queue}"))
                           .ContinueWith(x => length = x.Result);

                tasks[2] = _redisClient.LLenAsync(_storage.GetRedisKey($"queue:{queue}:dequeued"))
                           .ContinueWith(x => fetched = x.Result);
                Task.WaitAll(tasks);

                var jobs = GetJobsWithProperties(
                    redis,
                    firstJobIds,
                    new[] { "State" },
                    new[] { "EnqueuedAt", "State" },
                    (job, jobData, state) => new EnqueuedJobDto
                {
                    Job             = job,
                    State           = jobData[0],
                    EnqueuedAt      = JobHelper.DeserializeNullableDateTime(state[0]),
                    InEnqueuedState = jobData[0].Equals(state[1], StringComparison.OrdinalIgnoreCase)
                });

                result.Add(new QueueWithTopEnqueuedJobsDto
                {
                    Name      = queue,
                    FirstJobs = jobs,
                    Length    = length,
                    Fetched   = fetched
                });
            }

            return(result);
        });
Exemple #11
0
 public JobList <ScheduledJobDto> ScheduledJobs(int @from, int count)
 {
     return(UseConnection(connection => GetJobs(
                              connection,
                              from, count,
                              ScheduledState.StateName,
                              (sqlJob, job, stateData) => new ScheduledJobDto
     {
         Job = job,
         InScheduledState = ScheduledState.StateName.Equals(sqlJob.StateName, StringComparison.OrdinalIgnoreCase),
         EnqueueAt = JobHelper.DeserializeNullableDateTime(stateData["EnqueueAt"]) ?? DateTime.MinValue,
         ScheduledAt = sqlJob.StateChanged
     })));
 }
        public JobList <SucceededJobDto> SucceededJobs(int from, int count)
        {
            List <KeyValuePair <string, SucceededJobDto> > result = GetJobsOnState(States.SucceededState.StateName, from, count, (state, job) => new SucceededJobDto
            {
                Job           = job,
                Result        = state.Data.ContainsKey("Result") ? state.Data["Result"] : null,
                TotalDuration = state.Data.ContainsKey("PerformanceDuration") && state.Data.ContainsKey("Latency")
                                ? (long?)long.Parse(state.Data["PerformanceDuration"]) + long.Parse(state.Data["Latency"])
                                : null,
                SucceededAt = JobHelper.DeserializeNullableDateTime(state.Data["SucceededAt"])
            }).OrderByDescending(j => j.Value.SucceededAt).ToList();

            return(new JobList <SucceededJobDto>(result));
        }
        public JobList <ScheduledJobDto> ScheduledJobs(int from, int count)
        {
            return(UseConnection(redis =>
            {
                var scheduledJobs = redis.SortedSetRangeByRankWithScores(
                    Redis.Prefix + "schedule",
                    from,
                    from + count - 1);

                if (scheduledJobs.Length == 0)
                {
                    return new JobList <ScheduledJobDto>(new List <KeyValuePair <string, ScheduledJobDto> >());
                }

                var jobs = new Dictionary <string, Task <RedisValue[]> >();
                var states = new Dictionary <string, Task <RedisValue[]> >();
                var Tasks = new Task[scheduledJobs.Length * 2];
                int i = 0;

                var batch = redis.CreateBatch();
                foreach (var scheduledJob in scheduledJobs)
                {
                    var JobTask = batch.HashGetAsync(String.Format(Redis.Prefix + "job:{0}", scheduledJob.Element), new RedisValue[] { "Type", "Method", "ParameterTypes", "Arguments" });
                    Tasks[i++] = JobTask;
                    jobs.Add(scheduledJob.Element, JobTask);

                    var StatesTask = batch.HashGetAsync(String.Format(Redis.Prefix + "job:{0}:state", scheduledJob.Element), new RedisValue[] { "State", "ScheduledAt" });
                    Tasks[i++] = StatesTask;
                    states.Add(scheduledJob.Element, StatesTask);
                }
                batch.Execute();
                Task.WaitAll(Tasks);

                return new JobList <ScheduledJobDto>(scheduledJobs
                                                     .Select(job => new KeyValuePair <string, ScheduledJobDto>(
                                                                 job.Element,
                                                                 new ScheduledJobDto
                {
                    EnqueueAt = JobHelper.FromTimestamp((long)job.Score),
                    Job = TryToGetJob(jobs[job.Element].Result[0], jobs[job.Element].Result[1], jobs[job.Element].Result[2], jobs[job.Element].Result[3]),
                    ScheduledAt =
                        states[job.Element].Result.Length > 1
                                    ? JobHelper.DeserializeNullableDateTime(states[job.Element].Result[1])
                                    : null,
                    InScheduledState =
                        ScheduledState.StateName.Equals(states[job.Element].Result[0], StringComparison.OrdinalIgnoreCase)
                }))
                                                     .ToList());
            }));
        }
Exemple #14
0
        private JobList <EnqueuedJobDto> EnqueuedJobs(HangfireDbContext connection, IEnumerable <int> jobIds)
        {
            var jobs = connection.HangfireJobRepository
                       .Where(_ => jobIds.Contains(_.Id))
                       .ToList();

            //SQLITE PCL LIMITED LAMBDA SUPPORT!!
            var enqueuedJobs = connection.JobQueueRepository
                               .Where(_ => _.FetchedAt == DateTime.MinValue)
                               .ToList()
                               .Where(_ => jobs.Select(x => x.Id).Contains(_.JobId))
                               .ToList();

            var jobsFiltered = enqueuedJobs
                               .Select(jq => jobs.FirstOrDefault(job => job.Id == jq.JobId));

            var joinedJobs = jobsFiltered
                             .Where(job => job != null)
                             .Select(job =>
            {
                var state = connection.StateRepository.LastOrDefault(_ => _.JobId == job.Id);

                return(new JobDetailedDto
                {
                    Id = job.Id,
                    InvocationData = job.InvocationData,
                    Arguments = job.Arguments,
                    CreatedAt = job.CreatedAt,
                    ExpireAt = job.ExpireAt,
                    FetchedAt = null,
                    StateName = job.StateName,
                    StateReason = state?.Reason,
                    StateData = JsonConvert.DeserializeObject <Dictionary <string, string> >(state?.Data)
                });
            })
                             .ToList();


            return(DeserializeJobs(
                       joinedJobs,
                       (sqlJob, job, invocationData, stateData) => new EnqueuedJobDto
            {
                Job = job,
                InvocationData = invocationData,
                State = sqlJob.StateName,
                EnqueuedAt = sqlJob.StateName == EnqueuedState.StateName
                        ? JobHelper.DeserializeNullableDateTime(stateData.ContainsKey("EnqueuedAt") ? stateData["EnqueuedAt"] : string.Empty)
                        : null
            }));
        }
        //TODO: need test Query.In method
        private JobList <EnqueuedJobDto> EnqueuedJobs(HangfireDbContext connection, IEnumerable <int> jobIds)
        {
            var jobs = connection.Job
                       .Find(x => jobIds.Contains(x.Id))
                       .ToList();



            var enqueuedJobs = connection.JobQueue
                               .Query()
                               //.Where(x=>x.FetchedAt == null && jobs.Select(c=>c.Id).ToArray().Contains(x.JobId))
                               // V5 Weirdness: Splitting this to two separate statements worked, but keeping it as one fails!
                               .Where(x => x.FetchedAt == null)
                               .Where(x => jobs.Select(c => c.Id).ToArray().Contains(x.JobId))
                               .ToList();

            var jobsFiltered = enqueuedJobs
                               .Select(jq => jobs.FirstOrDefault(job => job.Id == jq.JobId));

            var joinedJobs = jobsFiltered
                             .Where(job => job != null)
                             .Select(job =>
            {
                var state = job.StateHistory.LastOrDefault();
                return(new JobDetailedDto
                {
                    Id = job.Id,
                    InvocationData = job.InvocationData,
                    Arguments = job.Arguments,
                    CreatedAt = job.CreatedAt,
                    ExpireAt = job.ExpireAt,
                    FetchedAt = null,
                    StateName = job.StateName,
                    StateReason = state?.Reason,
                    StateData = state?.Data
                });
            })
                             .ToList();

            return(DeserializeJobs(
                       joinedJobs,
                       (sqlJob, job, stateData) => new EnqueuedJobDto
            {
                Job = job,
                State = sqlJob.StateName,
                EnqueuedAt = sqlJob.StateName == EnqueuedState.StateName
                        ? JobHelper.DeserializeNullableDateTime(stateData["EnqueuedAt"])
                        : null
            }));
        }
        public JobList <ScheduledJobDto> ScheduledJobs(int from, int count)
        {
            return(UseConnection(redis =>
            {
                var scheduledJobs = redis.ZRangeByScoreWithScores(_storage.GetRedisKey("schedule"), from, from + count - 1);
                if (scheduledJobs.Length == 0)
                {
                    return new JobList <ScheduledJobDto>(new List <KeyValuePair <string, ScheduledJobDto> >());
                }

                var jobs = new ConcurrentDictionary <string, List <string> >();
                var states = new ConcurrentDictionary <string, List <string> >();;

                //var pipeline = redis.StartPipe();
                //var tasks = new Task[scheduledJobs.Length * 2];
                int i = 0;
                foreach (var scheduledJob in scheduledJobs)
                {
                    var jobId = scheduledJob;
                    var v1 = _redisClient.HMGet(
                        _storage.GetRedisKey($"job:{jobId}"),
                        new string[] { "Type", "Method", "ParameterTypes", "Arguments" });

                    jobs.TryAdd(jobId.member, v1.ToList());
                    i++;
                    var v2 = _redisClient.HMGet(
                        _storage.GetRedisKey($"job:{jobId}:state"),
                        new string[] { "State", "ScheduledAt" });
                    states.TryAdd(jobId.member, v2.ToList());
                    i++;
                }

                return new JobList <ScheduledJobDto>(scheduledJobs
                                                     .Select(job => new KeyValuePair <string, ScheduledJobDto>(
                                                                 job.member,
                                                                 new ScheduledJobDto
                {
                    EnqueueAt = JobHelper.FromTimestamp((long)job.score),
                    Job = TryToGetJob(jobs[job.member][0], jobs[job.member][1], jobs[job.member][2], jobs[job.member][3]),
                    ScheduledAt =
                        states[job.member].Count > 1
                                    ? JobHelper.DeserializeNullableDateTime(states[job.member][1])
                                    : null,
                    InScheduledState =
                        ScheduledState.StateName.Equals(states[job.member][0], StringComparison.OrdinalIgnoreCase)
                }))
                                                     .ToList());
            }));
        }
Exemple #17
0
        public JobList <ScheduledJobDto> ScheduledJobs(int from, int count) => UseConnection(redis =>
        {
            var scheduledJobs = redis
                                .SortedSetRangeByRankWithScores(_storage.GetRedisKey("schedule"), from, from + count - 1);

            if (scheduledJobs.Length == 0)
            {
                return(new JobList <ScheduledJobDto>(Enumerable.Empty <KeyValuePair <string, ScheduledJobDto> >()));
            }

            var jobProperties   = new RedisValue[] { "Type", "Method", "ParameterTypes", "Arguments" };
            var stateProperties = new RedisValue[] { "State", "ScheduledAt" };

            var jobs   = new ConcurrentDictionary <string, string[]>(StringComparer.OrdinalIgnoreCase);
            var states = new ConcurrentDictionary <string, string[]>(StringComparer.OrdinalIgnoreCase);;

            var pipeline = redis.CreateBatch();
            var tasks    = new Task[scheduledJobs.Length * 2];

            var i = 0;
            foreach (var job in scheduledJobs)
            {
                var jobId = (string)job.Element;

                tasks[i++] = pipeline.HashGetAsync(_storage.GetRedisKey($"job:{jobId}"), jobProperties)
                             .ContinueWith(x => jobs.TryAdd(jobId, x.Result.ToStringArray()), ContinuationOptions);

                tasks[i++] = pipeline.HashGetAsync(_storage.GetRedisKey($"job:{jobId}:state"), stateProperties)
                             .ContinueWith(x => states.TryAdd(jobId, x.Result.ToStringArray()), ContinuationOptions);
            }

            pipeline.Execute();
            pipeline.WaitAll(tasks);

            return(new JobList <ScheduledJobDto>(scheduledJobs
                                                 .Select(job =>
            {
                var jobId = (string)job.Element;
                var state = states[jobId];

                return new KeyValuePair <string, ScheduledJobDto>(jobId, new ScheduledJobDto
                {
                    EnqueueAt = JobHelper.FromTimestamp((long)job.Score),
                    Job = TryToGetJob(jobs[jobId], 0),
                    ScheduledAt = JobHelper.DeserializeNullableDateTime(state[1]),
                    InScheduledState = ScheduledState.StateName.Equals(state[0], StringComparison.OrdinalIgnoreCase)
                });
            })));
        });
Exemple #18
0
        private JobList <EnqueuedJobDto> EnqueuedJobs(HangfireDbContext connection, IEnumerable <int> jobIds)
        {
            List <JobDto> jobs = connection.Job
                                 .Find(Builders <JobDto> .Filter.In(_ => _.Id, jobIds))
                                 .ToList();

            Dictionary <int, JobQueueDto> jobIdToJobQueueMap = connection.JobQueue
                                                               .Find(Builders <JobQueueDto> .Filter.In(_ => _.JobId, jobs.Select(job => job.Id))
                                                                     & (Builders <JobQueueDto> .Filter.Not(Builders <JobQueueDto> .Filter.Exists(_ => _.FetchedAt))
                                                                        | Builders <JobQueueDto> .Filter.Eq(_ => _.FetchedAt, null)))
                                                               .ToList().ToDictionary(kv => kv.JobId, kv => kv);

            Dictionary <int, StateDto> jobIdToStateMap = connection.State
                                                         .Find(Builders <StateDto> .Filter.In(_ => _.Id, jobs.Select(job => job.StateId)))
                                                         .ToList().ToDictionary(kv => kv.JobId, kv => kv);

            IEnumerable <JobDto> jobsFiltered = jobs.Where(job => jobIdToJobQueueMap.ContainsKey(job.Id));

            List <JobDetailedDto> joinedJobs = jobsFiltered
                                               .Select(job =>
            {
                var state = jobIdToStateMap.ContainsKey(job.Id) ? jobIdToStateMap[job.Id] : null;
                return(new JobDetailedDto
                {
                    Id = job.Id,
                    InvocationData = job.InvocationData,
                    Arguments = job.Arguments,
                    CreatedAt = job.CreatedAt,
                    ExpireAt = job.ExpireAt,
                    FetchedAt = null,
                    StateId = job.StateId,
                    StateName = job.StateName,
                    StateReason = state?.Reason,
                    StateData = state?.Data
                });
            })
                                               .ToList();

            return(DeserializeJobs(
                       joinedJobs,
                       (sqlJob, job, stateData) => new EnqueuedJobDto
            {
                Job = job,
                State = sqlJob.StateName,
                EnqueuedAt = sqlJob.StateName == EnqueuedState.StateName
                        ? JobHelper.DeserializeNullableDateTime(stateData["EnqueuedAt"])
                        : null
            }));
        }
        public void CheckDefaultConstructor()
        {
            var watcher = new FetchedJobsWatcher(Redis.Storage);

            var redis = Redis.Storage.GetDatabase();

            // Arrange
            redis.SetAdd(Prefix + "queues", "my-queue", 0);
            redis.ListLeftPush(Prefix + "queue:my-queue:dequeued", "my-job");

            watcher.Execute(_cts.Token);

            Assert.NotNull(JobHelper.DeserializeNullableDateTime(
                               redis.HashGet(Prefix + "job:my-job", "Checked")));
        }
Exemple #20
0
 public List <FailedJobDto> GetFailedJobs(int from, int count)
 {
     return(GetJobs <FailedJobDto>(FailedState.DefaultName, from, count, (job, stateData) =>
     {
         return new FailedJobDto()
         {
             JobInfo = job,
             Reason = job.StateReason,
             ExceptionDetails = stateData["ExceptionDetails"],
             ExceptionMessage = stateData["ExceptionMessage"],
             ExceptionType = stateData["ExceptionType"],
             FailedAt = JobHelper.DeserializeNullableDateTime(stateData["FailedAt"])
         };
     }));
 }
        private JobList <EnqueuedJobDto> EnqueuedJobs(IEnumerable <string> jobIds)
        {
            using (var repository = _storage.Repository.OpenSession()) {
                var jobs = repository.Load <RavenJob>(jobIds.Select(a => Repository.GetId(typeof(RavenJob), a)))
                           .Where(a => a != null && a.StateData != null);

                return(DeserializeJobs(jobs, (jsonJob, job, stateData) => new EnqueuedJobDto {
                    Job = job,
                    State = jsonJob.StateData.Name,
                    EnqueuedAt = jsonJob.StateData.Name == EnqueuedState.StateName
                        ? JobHelper.DeserializeNullableDateTime(stateData["EnqueuedAt"])
                        : null
                }));
            }
        }
 private DateTime?ExtractCompletionDT(Dictionary <string, string> stateData)
 {
     if (stateData.ContainsKey("SucceededAt"))
     {
         return(JobHelper.DeserializeNullableDateTime(stateData["SucceededAt"]));
     }
     if (stateData.ContainsKey("FailedAt"))
     {
         return(JobHelper.DeserializeNullableDateTime(stateData["FailedAt"]));
     }
     if (stateData.ContainsKey("DeletedAt"))
     {
         return(JobHelper.DeserializeNullableDateTime(stateData["DeletedAt"]));
     }
     return(null);
 }
Exemple #23
0
        public void Execute_MarksDequeuedJobAsChecked_IfItHasNoFetchedFlagSet()
        {
            var redis = RedisUtils.CreateClient();

            // Arrange
            redis.SetAdd("{hangfire}:queues", "my-queue");
            redis.ListRightPush("{hangfire}:queue:my-queue:dequeued", "my-job");

            var watcher = CreateWatcher();

            // Act
            watcher.Execute(_cts.Token);

            Assert.NotNull(JobHelper.DeserializeNullableDateTime(
                               redis.HashGet("{hangfire}:job:my-job", "Checked")));
        }
 /// <summary>
 /// 已删除的作业
 /// </summary>
 /// <param name="from">开始范围</param>
 /// <param name="count">数量</param>
 public JobList <DeletedJobDto> DeletedJobs(int @from, int count) =>
 UseConnection(redis =>
 {
     var deletedJobIds = redis.LRange(_storage.GetRedisKey("deleted"), @from, @from + count - 1);
     return(GetJobsWithProperties(
                redis,
                deletedJobIds,
                null,
                new[] { "DeletedAt", "State" },
                (job, jobData, state) => new DeletedJobDto
     {
         Job = job,
         DeletedAt = JobHelper.DeserializeNullableDateTime(state[0]),
         InDeletedState = DeletedState.StateName.Equals(state[1], StringComparison.OrdinalIgnoreCase)
     }));
 });
        public void Execute_MarksDequeuedJobAsChecked_IfItHasNoFetchedFlagSet()
        {
            var redis = Redis.Storage.GetDatabase();

            // Arrange
            redis.SetAdd(Prefix + "queues", "my-queue");
            redis.ListLeftPush(Prefix + "queue:my-queue:dequeued", "my-job");

            var watcher = CreateWatcher();

            // Act
            watcher.Execute(_cts.Token);

            Assert.NotNull(JobHelper.DeserializeNullableDateTime(
                               redis.HashGet(Prefix + "job:my-job", "Checked")));
        }
        private JobList <EnqueuedJobDto> EnqueuedJobs(HangfireDbContext connection, IEnumerable <string> jobIds)
        {
            var jobObjectIds = jobIds.Select(ObjectId.Parse);
            var jobs         = connection.Job
                               .Find(Builders <JobDto> .Filter.In(_ => _.Id, jobObjectIds))
                               .ToList();

            var filterBuilder = Builders <JobQueueDto> .Filter;
            var enqueuedJobs  = connection.JobQueue
                                .Find(filterBuilder.In(_ => _.JobId, jobs.Select(job => job.Id)) &
                                      (filterBuilder.Not(filterBuilder.Exists(_ => _.FetchedAt)) | filterBuilder.Eq(_ => _.FetchedAt, null)))
                                .ToList();

            var jobsFiltered = enqueuedJobs
                               .Select(jq => jobs.FirstOrDefault(job => job.Id == jq.JobId));

            var joinedJobs = jobsFiltered
                             .Where(job => job != null)
                             .Select(job =>
            {
                var state = job.StateHistory.LastOrDefault();
                return(new JobDetailedDto
                {
                    Id = job.Id,
                    InvocationData = job.InvocationData,
                    Arguments = job.Arguments,
                    CreatedAt = job.CreatedAt,
                    ExpireAt = job.ExpireAt,
                    FetchedAt = null,
                    StateName = job.StateName,
                    StateReason = state?.Reason,
                    StateData = state?.Data
                });
            })
                             .ToList();

            return(DeserializeJobs(
                       joinedJobs,
                       (sqlJob, job, stateData) => new EnqueuedJobDto
            {
                Job = job,
                State = sqlJob.StateName,
                EnqueuedAt = sqlJob.StateName == EnqueuedState.StateName
                        ? JobHelper.DeserializeNullableDateTime(stateData["EnqueuedAt"])
                        : null
            }));
        }
        private JobList <EnqueuedJobDto> EnqueuedJobs(
            SessionWrapper session,
            IEnumerable <int> jobIds)
        {
            var jobs = session.Query <_Job>().Where(i => jobIds.Contains(i.Id)).ToList();

            return(DeserializeJobs(
                       jobs,
                       (sqlJob, job, stateData) => new EnqueuedJobDto
            {
                Job = job,
                State = sqlJob.StateName,
                EnqueuedAt = sqlJob.StateName == EnqueuedState.StateName
                        ? JobHelper.DeserializeNullableDateTime(stateData["EnqueuedAt"])
                        : null
            }));
        }
Exemple #28
0
        public JobList <SucceededJobDto> SucceededJobs(int from, int count)
        {
            var toReturn = GetJobs(from, count,
                                   SucceededState.StateName,
                                   (jsonJob, job, stateData) => new SucceededJobDto {
                Job = job,
                InSucceededState = true,
                Result           = stateData.ContainsKey("Result") ? stateData["Result"] : null,
                TotalDuration    = stateData.ContainsKey("PerformanceDuration") && stateData.ContainsKey("Latency")
                        ? (long?)long.Parse(stateData["PerformanceDuration"]) +
                                   (long?)long.Parse(stateData["Latency"])
                        : null,
                SucceededAt = JobHelper.DeserializeNullableDateTime(stateData["SucceededAt"])
            });

            return(toReturn);
        }
Exemple #29
0
 public JobList <DeletedJobDto> DeletedJobs(int @from, int count)
 {
     return(UsingDatabase(db =>
     {
         return new JobList <DeletedJobDto>(db.GetTable <Entities.Job>()
                                            .Where(x => x.StateName == "Deleted")
                                            .OrderByDescending(x => x.Id)
                                            .Skip(from)
                                            .Take(count)
                                            .Select(x => new KeyValuePair <string, DeletedJobDto>(x.Id.ToString(), new DeletedJobDto()
         {
             Job = x.ToCommonJob(),
             DeletedAt = JobHelper.DeserializeNullableDateTime(x.ToStateData().Data["DeletedAt"])
         }))
                                            .ToList());
     }));
 }
Exemple #30
0
        public void Execute_MarksDequeuedJobAsChecked_IfItHasNoFetchedFlagSet()
        {
            using (var redis = RedisUtils.CreateClient())
            {
                // Arrange
                redis.AddItemToSet("hangfire:queues", "my-queue");
                redis.AddItemToList("hangfire:queue:my-queue:dequeued", "my-job");

                var watcher = CreateWatcher();

                // Act
                watcher.Execute(_cts.Token);

                Assert.NotNull(JobHelper.DeserializeNullableDateTime(
                                   redis.GetValueFromHash("hangfire:job:my-job", "Checked")));
            }
        }