Scheduling Hangfire Jobs With Varying Schedules Using Cron Expressions

Scheduling your own background jobs in .NET can be a pain. If you’re feeling brave or rather ambitious, you could write your own scheduler using out of the box .NET framework components, or you could use a library like Hangfire.  Hangfire enables you to schedule jobs, and manages the execution and retry logic.   Scheduled jobs survive a process restart which is a nice bonus.

Recently I was developing an application with a requirement for recurring jobs. Users of the application were to be able to schedule jobs daily, weekly, monthly, as well as every three and four months.   I used Hangfire’s recurring job scheduler method for this.  This particular method uses CRON Expressions to specify the job schedule, and allows the most flexibility.   Cron is a little weird getting used to, but I found a great website with some simple guidance and an expression interpreter so you can test out your expressions.  Head on over to http://cronsandbox.com/ and you’ll find an online cron expression checker that parses your cron expression and tells you based on that expression, when your scheduled jobs will run next.  Its a beautiful thing.

There are five parts of a cron expression, and they’re explained pretty well on this site.  Here’s an excerpt:

“Reminder of the crontab format…
mm – the minute, a value between 0 and 59
hh – the hour, a value between 0 and 23
D – day of the month, between 1 and 31
M – month, a value between 1 and 12
DoW – day-of-the-week, 0-6 (0 = Sunday)

Each of the five items can be expressions…
A ‘*’ means use all values.
Multiples: e.g. every 20 mins would be ‘0,20,40’.
Range: e.g. hourly in the evening ’19-23′.
Every nth ‘0-23/n’, ‘*/2’ would be every other.
‘*/1’ is valid crontab syntax, but is flagged here as a possibly unintended entry.” 

Building off this format, you can schedule jobs to occur at varying intervals such as the following.  (I’ve got them all starting at 8AM but you can specify your own start time)

Weekly:                                00 08 * * 1

Every month:                     00 08 01 1,2,3,4,5,6,7,8,9,10,11,12 *

Every three months:      00 08 01 1-12/3 *

Every year:                          “00 08 01 1-12/12 *

Happy scheduling!

 

 

Execute code in parallel using Parallel.For

If you’ve ever had code that executes repetitive tasks, consider executing them in parallel using the ParallelFor method in the System.​Threading.​Tasks Namespace.

In this example, I’ve made a dinner decision maker, that randomly decides what to eat for dinner for the next N days.  In our program, we’ll randomly select from dinner choices, and add them to a dictionary.

Its best to use a Concurrent Dictionary as a thread safe collection to add items to during a parallel loop.   Additions to the collection are performed by TryAdd().  We’ll add unique keys and values to the collection potentially at the same time.  The TryAdd() method returns true if the key/value pair was added successfully, false if already exists.  Keep in mind executing  code in parallel is not always the right choice, and can lead to some pitfalls.

In the code below, we’re executing a code block in parallel.  I’ve made the current thread sleep for a random amount of time inside the parallel block, as it seems to generate a more wide variety of dinners.  The code block could have been a named function instead.  The point is that the operating system will decide if and how to execute the code at run time.  It may result in a not so improved performance, or it may not.

 

Abstract Classes vs Interfaces in C#

When should you use an abstract class, when should you use an interface?  Here’s the lowdown on some of the reasons to choose one over another.  First, take a look at a very simple example of an abstract class and two classes that inherit from it.

   public abstract class ToastBase
    {
        public ToastBase()
        {
            Console.WriteLine("Toast bread in toaster");
        }

        public abstract void AddSpread();
    }

    public class PeanutButterToast : ToastBase
    { 
        public override void AddSpread()
        {
            Console.WriteLine("Spread peanut butter on toast");
        }
    }

    public class JellyToast : ToastBase
    {
        public override void AddSpread()
        {
            Console.WriteLine("Spread jelly on toast");
        }
    }

Setting aside technical reasons, one of the strongest benefits to using an abstract class is the ability to provide an invariant implementation of some functionality across all sub classes, while leaving other implementations up to the subclass.  In our example above, all types of toast must first be toasted in a toaster.  Then, depending on the type of toast, the subclass can add whatever type of spread it wants.

On to the technical side.  An abstract class cannot be instantiated.  It is meant to be inherited.  If a method is not marked as abstract in an abstract class, the implementation belongs to the abstract class.  Abstract methods are implicitly virtual, and are meant to be overridden by the subclass.  They have no implementation in the base class, and therefore no method body, just a signature.  An class can inherit from multiple interfaces, but only one abstract class.  Here’s a more real world example.  Imagine a website back end where we want to collect and process credit cards for online purchases.  We might implement an abstract class such as the following:

  public abstract class PaymentBase
    {

        public void ProcessPayment(int paymentID)
        {
            PaymentProcessor.SendPaymentRequest(paymentID);
            PaymentProcessor.HandlePaymentResult(paymentID);             
        }

        public abstract void CollectCardInfo();
    }

The abstract PaymentBase class dictates that no matter what way we collect card information in the front end website, we must always process the payment the same way.

Interfaces are like contracts that dictate all the functionality a class must have that implements it.  When you implement an interface, you must define a method body for all the method signatures in the definition.  Interfaces are great for dependency injection, which states that we should always program to an interface, not an implementation.  This is beyond the scope of this article, but warrants further reading if you’re not familiar with it.

Interfaces enable you do decorate additional classes of the same concept, adding functionality.  Consider the example below.  We have a Customer and a LoyalCustomer class.  They both implement the ICustomer interface.  While we can place an order for each type of customer using the same interface, we can apply a discount to a loyal customer.  Meanwhile, all throughout our application, we can use the ICustomer interface anywhere we refer to a customer, and pass either Customer or LoyalCustomer to the method.  This also allows us to extend Customer to additional custom types down the road.

   public interface IOrder
    {
       int OrderID { get; set; }
       decimal orderAmount { get; set; }
    }

    public interface ICustomer
    {
        void PlaceOrder(IOrder order);
    }
   
    public class Customer : ICustomer
    {
        public void PlaceOrder(IOrder order)
        {
            //work with order properties, etc
            int i = order.OrderID;
        }
    }

    public class LoyalCustomer : ICustomer
    {
        public void PlaceOrder(IOrder order)
        {
            //apply discount
            order.orderAmount -= 5;
        }
    }

That’s all for now.  I hope you enjoyed this post!