I have write generic method using hangfire .Net. Basically i want to achieve that i have generate one method and want to call it multiple times when ever it is required. My helper method is below:
public static void ScheduleBackGroundJob(Task<Action> _refmethod, DateTime _dateTime)
{
try
{
var _currentDate = DateTime.Now;
TimeSpan _timeSpan = _dateTime - _currentDate;
BackgroundJob.Schedule(() => _refmethod, _timeSpan);
}
catch (Exception ex)
{
throw ex;
}
}
I want to call this method using like this
HangfireHelper.ScheduleBackGroundJob(_service.UpdateAuctionStatus(result), result.PlannedCloseDate);
My updateAuctionStatus Method is below.
public void UpdateAuctionStatus(AuctionReturnModel model)
{
try
{
var _auction = (from d in _db.Auction_Detail where d.Id == model.AuctionDetailId select d).FirstOrDefault();
_auction.isEnded = true;
_db.Auction_Detail.Add(_auction);
_db.SaveChanges();
var _auctionHistory = new AuctionHistory { AuctionDetail_Id = model.AuctionDetailId, EndedDate = DateTime.Now, EndedMethod = "Automatic" };
_db.AuctionHistory.Add(_auctionHistory);
_db.SaveChanges();
Task.WaitAll();
}
catch (Exception ex)
{
throw ex;
}
}
My getting the above error cannot convert into void. I want to call it by sending any method as a parameter.
I have done it by changing my methods like
public static void ScheduleBackGroundJob(Expression<Action> _refmethod, DateTime _dateTime)
{
try
{
var _currentDate = DateTime.Now;
TimeSpan _timeSpan = _dateTime - _currentDate;
BackgroundJob.Schedule(_refmethod, _timeSpan);
}
catch (Exception ex)
{
throw ex;
}
}
Calling Hangfire helper code
HangfireHelper.ScheduleBackGroundJob(() => _service.UpdateAuctionStatus(result), result.PlannedCloseDate);
My service method i have change this
public async Task UpdateAuctionStatus(AuctionReturnModel model)
{
try
{
var _auction = await (from d in _db.Auction_Detail where d.Id == model.AuctionDetailId select d).FirstOrDefaultAsync();
_auction.isEnded = true;
_db.Auction_Detail.Add(_auction);
_db.SaveChanges();
var _auctionHistory = new AuctionHistory { AuctionDetail_Id = model.AuctionDetailId, EndedDate = DateTime.Now, EndedMethod = "Automatic" };
_db.AuctionHistory.Add(_auctionHistory);
_db.SaveChanges();
Task.WaitAll();
}
catch (Exception ex)
{
throw ex;
}
}
Hope this will help you in future. Any code reviews and best practices will be highly appreciated because i am always looking to learn something new and better approaches to solve problems.