Service Fabric Reminders - Time remaining to trigger - c#

Suppose I have a service fabric reminder which I registered via OnActivateAsync method. Now for these Service Fabric reminder via GetReminder method I can check whether a reminder already exists or not. But can I check when is this reminder scheduled to trigger next ?
For example I have registered a reminder with a period of 4 hours and it got triggered at 2PM ( schedule to trigger next at 6PM ). Now at 3:30 PM some of my other service want to know when is the next reminder scheduled. I can get this reminder via GetReminder method but I am unable to get the time remaining for its next execution.
Following this Doc - Actor timers and reminders

Use the reminder due date. Add periods while the result is smaller than the current time.
The first time it is larger, the difference is the time remaining until it fires next.

Related

C# - Best way to continuously check a process

Scenario: A Azure WebJob that will get all the Vendor record from NetSuite via WSDL.
Problem: The dataset is too large. Even with service set to 12 minutes time out. It still time out and the code failed.
NetSuite have a async process that basically run whatever you want on the server and it will return a JobId that allowed you to check the process on the server.
What I did currently is by making a search call first asking for all the Vendor records and it is to be process on the server. After I got the JobId, i wrote a void Recursion that check if the job is finish on the server with Thread Sleep set to 10 minutes.
private static bool ChkProcess(VendorsService vendorService, string jobId)
{
var isJobDone = false;
//Recursion
void ChkAsyncProgress(bool isFinish)
{
if (isFinish) return;
var chkJobProgress = vendorService.NsCheckProcessStatus(jobId);
if (chkJobProgress.OperationResult.IsFinish) isJobDone = true;
Thread.Sleep(TimeSpan.FromMinutes(10));
ChkAsyncProgress(isJobDone);
}
ChkAsyncProgress(false);
return isJobDone;
}
It work but is there a better approach?
Thanks
I think that since you're working with Azure already, with Service BUS you can implement a really low cost solution for this (if not free, depending on how much frequent is your job running)
Basically it's a queue where you enqueue messages (which can be objects with properties too, so they could also contain your result of the elaboration potentially).
A service bus is used to enqueue.
An azure function of type ServiceBusTrigger listens automatically if any new message on service bus has arrived and gets triggered if so (or, you can set messages to be enqueued, but be available after a certain future time only).
So, in the webjob code, at the end you could add code to enqueue a message which will mark the webjob has finished elaboration.
The azure function will get immediately noticed as soon as the message gets in the queue and you can retrieve the data without polling constantly for job completion, as azure will take care of all of that for you for a ridiculous price and without any effort by you.
Also, these task aren't priced timely based, but execution based, so you will pay only when it effectively put a message in queue.
They have a certain number of executions free, so it might be that you don't even need to pay anything.
Here some microsoft code sample for doing so.

How to create a self Time triggered Function?

Looking for some self triggering function which starts on a time given.
eg. A user has a conference to start at 25/04/2019 05:30
Here the user should get a notification at 25/04/2019 05:25 | 05:29 That the conference is about to start.
Have created a azure function (Time triggred) which triggers every minute and checks if current time is the Conference Time - 4 minutes, Then send a notification regarding conference to be started.
In future will have multiple users and so I do not want the function to run every minute, Is there a way in which at 05:25 or at the conference time the function will execute itself.
So there can be 100 users and they will have different. Just looking for options about how to implement in a better way.
.net core site,
hosted on azure,
Have azure functions running every minute to check the remainder
When user registered on conference you can queue message(with user details) to queue with visibility delay:
queue.AddMessage(message, initialVisibilityDelay: TimeSpanDelay);
For example, user registered at 6 PM, and conference will be next day at 8 PM, so delay time will be 25 hours and and 55 minutes(supposed, that user want to be notified 5 minutes before conference). Then instead of time triggered function you will use queue triggered function, which will send notifications, when messages from queue become visible:
public static void Run([QueueTrigger("notifications")]QueueTrigger message, TraceWriter log)
{
Notifier.Send(message.UserName, message.UserPhoneNumber, message.Email);
}
Moreover, if by some reason your notification handler will be failed, queue messages will not be lost, so you can retry to process them several times.
I recommend you to write a windows service using quartz library to schedule a job. You can pickup the job schedule time from db or somewhere.
Refer: https://www.quartz-scheduler.net
From your description, you already have a TimerTrigger Function however your Timer set the function running every minutes. Actually you could set more precise Timer trigger with CRON expressions.
This is CRON expressions in Azure Function, it includes six fields:{second} {minute} {hour} {day} {month} {day-of-week}. So you could set your Function 0 25,29 5 22 March *.
And after you deploy the function to Azure, it will keep running however it won't execute the Run method until it triggers the Timer.
public static void Run(TimerInfo myTimer, ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
}

Recurring Payment Code using PAYPAL

In our application we are having monthly subscription so on last date of the month amount should transfer from UserAccount to CompanyAccount?
How to do this after equal frequency?Like Mothly,Quaterly etc.
Please Help US.........
You can use Windows task scheduler to call specific web page or exe which will do transfer.
Set up one task scheduler to call transfer monthly and second to call quarterly.

Sending emails automatically

I'm working on an MVC .Net web application. I have a database in which i have a table called Tasks, every task is associated to one user and every task has a delay. I want to send emails automatically to the user to whom the task is associated before two days (for example) from its expiration date.
You can use Windows Service to send email automatically.
Please refer below link
http://www.dotnetfunda.com/articles/article931-how-to-send-mail-automatically-for-every-five-minutes-using-csharp.aspx
You can set the timer for 2 days with your logic.
You could write a Windows Service application or a Console application that will be scheduled to run at regular intervals using the Windows Scheduler (for example once a day), it will query your database, extract the records matching the required criteria and, yeah, SmtpClient.
The reason I am saying this is because this task should not be done by your web application. It should be performed by a separate application. Recurring background tasks such as the one you need to perform is a no-no in a web application. The Haacked discussed why this is a very bad idea: http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx
Little mock up example:
DateTime today = DateTime.Now;
TimeSpan diff = user.Tasks.ExpirationDate.Subtract(today);
int dateDiff = Convert.ToInt32(diff.TotalDays);
if (dateDiff == 2)
{
//Send Email
}
You could then place this in a Services/Email folder in your mvc app and create a separate console app to request the page everyday, therefore running the query, e.g:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("YOUR PAGE");
string response = new System.IO.StreamReader(req.GetResponse()
.GetResponseStream()).ReadToEnd();
You would use Windows Task Scheduler to run the console app every day which would start the console app > console app requests page > page checks expiration date on tasks > sends emails

Sending Periodic Mail according to user's Setting in ASP.net?

in my web-application I want to send mail for users according to pre selected periods by themselves. for example: 1 HTML Mail Per 3days to user 01 and 1 HTML Mail Per 20days to user 02
how can I perform that? any resources? I can send mail by my app from My Gmail Account to any mail addresses in my tables but i dont know how to send it automatically in a period of time.(i use C# and SQL Express)
Help me out!
I found the Solution. according to my search we have 3 ways to handle that:
working with SQL Server to send mail notification in periods of time.(or this)
using Windows service and Creating Timer object and checking the time with it.
but in ways 1 and 2 we should access to server and we need dedicated hosting server to for example installing WinService on it. so it does not work in a sharing Host space we usually use. So I Found the best way as you see:
3. Simulating Windows Services Using ASP.NET Caching For Scheduled Jobs.
the link above is a terrific solution. So there is no need to work out-side of our web application.
You will need something which can periodically run jobs for you, like a cron daemon or windows task scheduler.
Essentially you have the periodic job kick off and do whatever mail handling you need.
You can also do this from code if you can create a windows service to basically sleep until the next batch of mails needs to be sent.
The easiest is to write the task scheduler or cron job to run periodically. In that way you just need a small piece of code to handle the mail sending portion and then you just schedule it to run once an hour or day or whatever needed.
Hai,
Have a look at quartz.net
Quartz.NET is a full-featured, open source job scheduling system that can be used from smallest apps to large scale enterprise systems.
Quartz.NET is a port of very propular open source Java job scheduling framework, Quartz. Quartz.NET supports clustering and database persistence out-of-the-box and has powerful means to schedule jobs using cron like expressions, interval triggers and exclusion advices.
The great thing about IIS hosted ASP.NET is that IIS will (by default) periodically recycle your application pool according to the settings on the app pool itself.
When your application pool is starting (which could be at least once a day especially if it's allowed to idle i.e. a business app where most activity is 9-5) the Application_Start event-handler in Global.asax is fired. This could be used for your recurring task.
Now you don't necessarily want to run this email send synchronously within that Application_Start handler because to me it seems this messaging functionality is not core to the startup but by all means use this event-handler as an easy way to periodically do your housekeeping.
To send async you should use async delegates for example.
i think there a solution:
1- you have to add 2 column in the user table in your sql db if you have a user table and in the first column add the date of the last email sent to the user and the second column has the period for sending the email for that user for ex:
LastEmailSentDate datetime
SendEmailPeriod int
2- in your application code write a function that compare the last date of the last sent email with the period of the sending the email.
// here the funciton code
public void CompareLastSentDate()
{
// lets assume that you bring the data for the db using Sqdatareader reader
//get the field from the LastEmailSentDate field in the database as i mention before
DateTime LastEmailSentDate = Convert.ToDate(reader["DatePeriod"])
// get the field from the SendEmailPeriod of the user field from database
int sendEmailPeriod = Convert.Toint32(reader["SendEmailPeriod"])
// now you have the date before the period of day ex: before 3 days depend on user
DateTime DatePeriod = new DateTime(DateTime.Now.Year, DateTime.Now.Month, (DateTime.Now.Day - sendEmailPeriod ));
// if the last email send is before period of day that mean u have to send an email again
if(LastEmailSentDate.Day <= DatePeriod.Day)
{
// sent the email to the user
}
}
note: now u can loop among the users and sent the email
you can call this function once in a day by calling it from ur app home page Page_Load event and after the first call of the day add an application["LastFunctionCallDate"] = DateTime.Now flag so in the next you can check this flag if its == today and if not call it again

Categories