using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Abp.Domain.Entities.Auditing;
using Abp.MultiTenancy;
using Abp.Timing;
namespace Abp.BackgroundJobs
{
///
/// Represents a background job info that is used to persist jobs.
///
[Table("AbpBackgroundJobs")]
[MultiTenancySide(MultiTenancySides.Host)]
public class BackgroundJobInfo : CreationAuditedEntity
{
///
/// Maximum length of .
/// Value: 512.
///
public const int MaxJobTypeLength = 512;
///
/// Maximum length of .
/// Value: 1 MB (1,048,576 bytes).
///
public const int MaxJobArgsLength = 1024 * 1024;
///
/// Default duration (as seconds) for the first wait on a failure.
/// Default value: 60 (1 minutes).
///
public static int DefaultFirstWaitDuration { get; set; }
///
/// Default timeout value (as seconds) for a job before it's abandoned ().
/// Default value: 172,800 (2 days).
///
public static int DefaultTimeout { get; set; }
///
/// Default wait factor for execution failures.
/// This amount is multiplated by last wait time to calculate next wait time.
/// Default value: 2.0.
///
public static double DefaultWaitFactor { get; set; }
///
/// Type of the job.
/// It's AssemblyQualifiedName of job type.
///
[Required]
[StringLength(MaxJobTypeLength)]
public virtual string JobType { get; set; }
///
/// Job arguments as JSON string.
///
[Required]
[StringLength(MaxJobArgsLength)]
public virtual string JobArgs { get; set; }
///
/// Try count of this job.
/// A job is re-tried if it fails.
///
public virtual short TryCount { get; set; }
///
/// Next try time of this job.
///
//[Index("IX_IsAbandoned_NextTryTime", 2)]
public virtual DateTime NextTryTime { get; set; }
///
/// Last try time of this job.
///
public virtual DateTime? LastTryTime { get; set; }
///
/// This is true if this job is continously failed and will not be executed again.
///
//[Index("IX_IsAbandoned_NextTryTime", 1)]
public virtual bool IsAbandoned { get; set; }
///
/// Priority of this job.
///
public virtual BackgroundJobPriority Priority { get; set; }
static BackgroundJobInfo()
{
DefaultFirstWaitDuration = 60;
DefaultTimeout = 172800;
DefaultWaitFactor = 2.0;
}
///
/// Initializes a new instance of the class.
///
public BackgroundJobInfo()
{
NextTryTime = Clock.Now;
Priority = BackgroundJobPriority.Normal;
}
///
/// Calculates next try time if a job fails.
/// Returns null if it will not wait anymore and job should be abandoned.
///
///
public virtual DateTime? CalculateNextTryTime()
{
var nextWaitDuration = DefaultFirstWaitDuration * (Math.Pow(DefaultWaitFactor, TryCount - 1));
var nextTryDate = LastTryTime.HasValue
? LastTryTime.Value.AddSeconds(nextWaitDuration)
: Clock.Now.AddSeconds(nextWaitDuration);
if (nextTryDate.Subtract(CreationTime).TotalSeconds > DefaultTimeout)
{
return null;
}
return nextTryDate;
}
}
}