1

Hangfire is a background class method runner and it's recurring job function RecurringJob.AddOrUpdate(Expression< Action >,string) is the method used to add methods to the queue. The first parameter is an Action call and the second is a cron formatted string.

If I have strings of the class and function name, how could I add a job.

Example normal non string call would be:

RecurringJob.AddOrUpdate(() => new MyClass().MyMethod(), "0 0 * * *");

I'd like to do something like

string myClassString = GetMyClassFromConfig();//value "MyNamespace.MyClass";
string myMethodString = GetMyMethodFromConfig();//value "MyMethod";
string myCronString = GetMyCronFromConfig();// value "0 0 * * *"
Type myType = Type.GetType(myClassString);
var myMethod = myType.GetMethod(myMethodString);
var myInstance = Expression.Parameter(myType,"instanceName");
RecurringJob.AddOrUpdate(Expression.Call(myInstance,myMethod), myCronString);

but this is throwing an error on the AddOrUpdate method call:

Could not create an instance of type System.Linq.Expressions.Expression. Type is an interface or abstract class and cannot be instantiated. Path 'Type', line 1, position 8.

How would I add jobs via string definitions or how would I make the Expression < Action > from strings that would allow the object instantiation and method running(new MyClass().Run()) shown in the upper sample?

gjutras
  • 65
  • 1
  • 8
  • Possible duplicate of [How to convert a String to its equivalent Expression Tree?](http://stackoverflow.com/questions/821365/how-to-convert-a-string-to-its-equivalent-expression-tree) – DLeh Oct 29 '15 at 12:51
  • The string to its equivalent expression tree question/answer doesn't help me return an Expression or Expression> from strings, where the Action or Func can be inclusive or an object instantiation (new MyClass()) that is required by the hangfire addorupdate method. – gjutras Oct 29 '15 at 13:15
  • trying to parse and run an `Action` would be like running dynamic code, which is probably not possible in c# http://stackoverflow.com/questions/4629/how-can-i-read-the-properties-of-a-c-sharp-class-dynamically – DLeh Oct 29 '15 at 13:19
  • @DLeh You are misinterpreting the answer to that question. It is possible, just not built in and takes some extra work to do. And for some simple functions [`DataBinder.Eval`](https://msdn.microsoft.com/en-us/library/system.web.ui.databinder.eval(v=vs.110).aspx) may be able to do it out of the box. – Scott Chamberlain Oct 29 '15 at 13:47

1 Answers1

3

The following would do the job

// ... (same as yours except the last 2 lines)
var myAction = Expression.Lambda<Action>(Expression.Call(Expression.New(myType), myMethod));
RecurringJob.AddOrUpdate(myAction, myCronString);
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343