Skip to content

Instantly share code, notes, and snippets.

@odinserj
Created April 26, 2017 08:56
Show Gist options
  • Save odinserj/3beba58003ae5bdb817f71ce9b22c01e to your computer and use it in GitHub Desktop.
Save odinserj/3beba58003ae5bdb817f71ce9b22c01e to your computer and use it in GitHub Desktop.
Pause Batches
using System;
using System.Collections.Generic;
using Hangfire;
using Hangfire.Common;
using Hangfire.States;
using Hangfire.Storage;
namespace ConsoleApp18
{
public class CanBePausedAttribute : JobFilterAttribute, IElectStateFilter
{
public void OnStateElection(ElectStateContext context)
{
if (!(context.CandidateState is ProcessingState)) return;
var batchId = context.GetJobParameter<string>("BatchId");
if (String.IsNullOrEmpty(batchId)) return;
var storageConnection = context.Connection as JobStorageConnection;
if (storageConnection == null) return;
var paused = storageConnection.GetValueFromHash($"batch:{batchId}", "IsPaused");
if (bool.TryParse(paused, out bool isPaused) && isPaused)
{
context.CandidateState = new ScheduledState(TimeSpan.FromSeconds(15))
{
Reason = "Batch is paused"
};
}
}
}
public static class JobStorageExtensions
{
public static void PauseBatch(this JobStorage storage, string batchId, bool value)
{
if (storage == null) throw new ArgumentNullException(nameof(storage));
if (batchId == null) throw new ArgumentNullException(nameof(batchId));
using (var connection = storage.GetConnection())
{
connection.SetRangeInHash($"batch:{batchId}", new []{ new KeyValuePair<string, string>("IsPaused", value.ToString()) });
}
}
}
class Program
{
static void Main(string[] args)
{
GlobalConfiguration.Configuration
.UseFilter(new CanBePausedAttribute())
.UseRedisStorage()
.UseBatches();
var batchId = BatchJob.StartNew(x =>
{
x.Enqueue(() => Console.WriteLine("Hello, world 1"));
x.Enqueue(() => Console.WriteLine("Hello, world 2"));
});
JobStorage.Current.PauseBatch(batchId, true);
using (new BackgroundJobServer())
{
Console.ReadLine();
JobStorage.Current.PauseBatch(batchId, false);
Console.ReadLine();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment