how to start windows service on particular time - c#

i want to start my windows service on every sunday 1.00 A.M.
can anyone help me in this

If it has to run on every sunday 1.00 AM then probably you need a simple program that is run by task scheduler on 1 AM Sunday.
It would be better if you use a timer that fires say every one hour and check what day and time it is. If it is sunday and 1 AM you can disable the timer and carry on with the work you want to do in the service. After the work is done then you should re-enable the timer.

One way could be to use SC command in a batch file which can be scheduled to run from windows standard scheduler.
For more information, see
SC /?
start and stop parameters in particular.

Since the logic should be done once in a week at a particular time use windows task scheduler for your purpose.
If you do not know how to perform this, Create a sample.vbs file, which calls your asp.net page/web service where you perform the logic. Then create a schedule in windows task scheduler to trigger your sample.vbs file.
Please see the steps to create the .vbs file that calls your asp.net page/web service
1.Open notepad and copy the following code in it and save
'Declare variables
Dim objRequest
Dim URL
Set objRequest = CreateObject("Microsoft.XMLHTTP")
'Put together the URL link appending the Variables.
URL = "http://computerName/VirtualDirectoryName/Logic.aspx"
'Open the HTTP request and pass the URL to the objRequest object
objRequest.open "POST", URL , false
'Send the HTML Request
objRequest.Send
'Set the object to nothing
Set objRequest = Nothing
2.Edit the URL="with your virtual directory path to the asp.net page/web service" and save.
3.change the extension from ".txt" to ".vbs" and save.
4.Create a new schedule in windows "Task Scheduler" and point the newly created sample.vbs file which will call the page where your logic is written (http://computerName/VirtualDirectoryName/Logic.aspx) and edit the settings to run once in a week at a particular time.

The way I do it is like this:
First you install your windows service on your Windows Server.
Second, you make a batch file. You just open Notepad, write the line beneath and save it as a .bat.
net start myService
Then you use the Task Scheduler available in Windows Server.
Creating the task is easy, you just need to add a trigger event (every sunday) and an action (starting the batch file you've just created).
I'm not saying it is the best way, but it is a way that will work.

Related

How to call "Action Result" ASP.NET MVC at specific time (Daily)

I have a system for sending E-mails to users by a specific time .
built in ASP.NET MVC4 and has an action result "function" for checking the time of messages and send it if the day of the message is today .
how can I call this action result (daily) -like a scheduler- in efficient way ?
Thanks.
Whilst a separate service / application would be better, you could use wget.
GNU Wget is a free software package for retrieving files using HTTP,
HTTPS and FTP, the most widely-used Internet protocols. It is a
non-interactive commandline tool, so it may easily be called from
scripts, cron jobs, terminals without X-Windows support, etc.
You would then do something like:
"C:\Program Files (x86)\GnuWin32\bin\wget.exe" --no-check-certificate https://www.exammple.com/YouController/YourAction -O NUL
in a .bat file and set that to run via a windows Scheduled task at the time you require (assuming you don't need to run it less than every 60 seconds - if you do, let me know as I have another way around this using a windows service to call the bat file instead).
Omitting the -O NUL part would also save the output so you could see if everything ran successfully by doing:
public ActionResult YourAction()
{
//Do your code, get some stats that show it ran properly.
return Content("Return your stats here.");
}
from your controller action.
More efficient will be when you create new application as Windows Service. There u can easy set code to start at specific time. in this solution you will have more flexibility and independent. You can start hire : Windows Service to run a function at specified time
You could create a small console application that just calls the API do send out the emails. You can then schedule the console app to run at a specific time using the Windows Scheduler; you can even have it run without showing the console window. See here or here for details on how to schedule a task.
Use Azure Functions, that's exactly what it was built for. It's really good.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-overview

Starting an existing Mainframe job with FTP and C#

We have a lot of jobs(jcl) running on the mainframe.
I was asked to try and start a restore job. I have to do this with a C# application.
What i got now is i am able to connect to the mainframe with an ftp library and I can call raw FTP commands that the mainframe understands.
I kind of know how to submit a .jcl file, which will be processed as a job if I use the command "quote site filetype=jes".
My questions are:
- Is there a way to start an existing job?
- Does it matter what "directory"/partition(?) I have navigated to before submitting a job?
You could submit the below JCL through FTP and it would run the JCL in JOB.LIBRARY(JOB)
//JS010 EXEC PGM=IEBGENER
//SYSUT1 DD DSN=JOB.LIBRARY(JOB),DISP=SHR
//SYSUT2 DD SYSOUT=(,INTRDR)
//SYSPRINT DD SYSOUT=*
//SYSIN DD DUMMY
Expanding on Bills comments, is this a Production, Development, Test, QA etc job.
In production on mainframe's, jobs are normally run using a Scheduler (e.g. Ca7 or Workload Scheduler for z/OS (formerly OPC) + several others). Some sites also use Schedulers in QA / Development as well, but this is rare.
Submitting a job via a scheduler
To submit via a scheduler you MUST talk to the Operations / Production Control / Mainframe Support department. They should know what is possible and have preferred ways of doing something like this. They should also know what access is required !!!
Possible options would include:
Most schedulers have the option of submitting a job / schedule when a Dataset (File for non-mainframer's) is created. If available this will probably be the easiest to implement.
All schedulers provide programs that can submit schedules.
You may be able to run a job that submits the appropriate job
Run a program in the foreground to submit the appropriate job
These days most of the schedulers would have a Web interface, they may also have interfaces on other platform. This option is probably not going to be available though.
Submitting a job
If you are just going submit the job, options include:
Copying the job to the INTRDR as #Deuian has done (either foreground or background).
Running TSO background
Submitting via job (from Deuian's answer):
//JOBNAME JOB ...
//JS010 EXEC PGM=IEBGENER
//SYSUT1 DD DSN=JOB.LIBRARY(JOB),DISP=SHR
//SYSUT2 DD SYSOUT=(,INTRDR)
//SYSPRINT DD SYSOUT=*
//SYSIN DD DUMMY
Finally to do anything on the Mainframe, you will need the appropriate security access !!!
I have tried to provide a background information + a basic guide of the option available. Basically you need to talk to Mainframe-Operation / Mainframe-programmers !!!.
Yes, you can - just execute the RETR 'DATASET.NAME' FTP command. Remember that the quotes here are important - without quotes the command would be interpreted as "read spool files by JOBID". And with quotes it would be interpreted as "submit an existing JCL data set, wait for job to complete and retrieve it's spool". And it doesn't matter what directory you have navigated to before submitting a job.
You can refer to my Java implementation of JES client which works through FTP - https://github.com/vadimshchukin/jesclient. It has code which does exactly what you want:
public JESJob execute(String datasetName) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
retrieveFile(String.format("'%s'", datasetName), outputStream);
JESJob job = new JESJob(this);
job.setSpool(outputStream.toString());
return job;
}

Where to define scripts that deletes files older then 7 days

I need to write script that delete files older than 7 days in MVC .Net application. I'm going to use this code
List<string> DeletePath = new List<string>();
DirectoryInfo info = new DirectoryInfo(Server.MapPath("~\\TempFiles"));
FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();
foreach (FileInfo file in files)
{
DateTime CreationTime = file.CreationTime;
double days = (DateTime.Now - CreationTime).TotalDays;
if (days > 7)
{
string delFullPath = file.DirectoryName + "\\" + file.Name;
DeletePath.Add(delFullPath);
}
}
foreach (var f in DeletePath)
{
if (File.Exists(F))
{
File.Delete(F);
}
}
But i don't know where to define this and how to call. Do i need to create new Controller or something similar?
wrap your code in a static method and use hangfire
http://docs.hangfire.io/en/latest/background-methods/performing-recurrent-tasks.html
RecurringJob.AddOrUpdate(() => myCleanup.CleanupOldFiles(), Cron.Hourly)
Well you need to create a window service which will run in background on the server. Window services are the normal application which run automatically without any user event. Create a window service, then you can write the same code there wrapped in a timer tick event. There you can set the time when you want to execute this code.
Usually window service once deployed start executing your code every second. So you need to set the clock. With the Timer, you can execute your code as per your requirement, everyday at particular time, once in a week, once in a month or so on so forth.
Read more about window services here...
and let me know if you need code for this.
Mvc is not the job for this. It's like asking how to install tires on a train so that it can drive up a private street.
In order for Mvc or any web application for that matter to do something, a request must come in from a client. If no request comes in, IIS does nothing and just "listens" for incoming connections. To do this the "correct" way, you have two options:
Create a batch file or Powershell script or even a C# console application that deletes the files, then setup that batch file or script or program to run in Windows Task Scheduler.
If you need more logic to determine when the files should be deleted or you need customized schedules, then you should make a Windows Service Application. You can make this in C# and you can pretty much have it do anything you want, so long as it doesn't need a GUI. If you do need a GUI, perhaps to configure the service, then you can make a separate WinForms or WPF application that can configure the service. There are several ways to implement GUI/Service communication. Some of the more popular ones are WCF communication, database configuration or even INI files.
Hope this helps!

how to create cron job in asp.net(v4.0) to run method every 30mins

I need some guidance on creating and running a Cron Job in asp.net(C#.net) to run every 30 minutes.i have created a class in that i have written code for getting tweets, facebook feeds.
i have created another page in that i have one button to download tweets and save in database.
If i want to get tweets i have to click on sync button every time.
i want to create cron job so that the database will get automatically synchronized with new tweets,facebook feeds.
Thanks
You can follow any one of the following approaches
Create a console app with the logic to fetch the tweets and feeds, and use a Task scheduler to run it for every 30 mins.
You could build a windows service, which polls the feeds within a timer and updates the db.
You could checkout this scheduler which is a rough equivalent to cron jobs. Personally haven't tried it. Check out this SO
If your intended 30-minute scheduled task is meant to be a discrete transactional action (like, for instance, your example of synchronizing some database values), then you may want to take a look at the Revalee open source project.
You can use it to schedule web callbacks at specific times. In your case, you could schedule a web callback (30 minutes in the future). When your ASP.NET application receives the callback, it can schedule the next 30 minute callback as well as perform whatever tasks you need it to handle every half-hour. When your ASP.NET application launches for the very first time, then you would schedule the first web callback. Since your web application is being called back, you do not need to worry about your web application unloading (which it will do periodically on IIS, for example).
For example using Revalee, you might do the following:
Register a future (30 minutes from now) callback when your application launches via the ScheduleThirtyMinuteCallback() method (see below).
private DateTimeOffet? previousCallbackTime = null;
private void ScheduleThirtyMinuteCallback()
{
// Schedule your callback 30 minutes from now
DateTimeOffset callbackTime = DateTimeOffset.Now.AddMinutes(30.0);
// Your web service's Uri, including any query string parameters your app might need
Uri callbackUrl = new Uri("http://yourwebapp.com/Callback.aspx");
// Register the callback request with the Revalee service
RevaleeRegistrar.ScheduleCallback(callbackTime, callbackUrl);
previousCallbackTime = callbackTime;
}
When the web scheduled task activates and calls your application back, you perform whatever action you need to do every 30 minutes and you schedule the next callback too. You do this by adding the following method call (CallbackMonitor()) to your Callback.aspx page handler.
private void CallbackMonitor()
{
if (!previousCallbackTime.HasValue
|| previousCallbackTime.Value <= DateTimeOffset.Now.AddMinutes(-30.0))
{
// Perform your "30 minutes have elapsed"-related tasks
// ...do your work here...
// Schedule subsequent 30 minute callback
ScheduleThirtyMinuteCallback();
}
}
To be clear, the Revalee Service is not an external 3rd party online scheduler service, but instead a Windows Service that you install and fully control on your own network. It resides and runs on a server of your own choosing, most likely your web server (but this is not a requirement), where it can receive callback registration requests from your ASP.NET application.
If, however, your 'run every 30 minutes' task is a long running task, then you probably do not want to embed that functionality within your ASP.NET application.
I hope this helps.
Disclaimer: I was one of the developers involved with the Revalee project. To be clear, however, Revalee is free, open source software. The source code is available on GitHub.

Whats the best way to run a time consuming script in ASP.NET at regular intervals on shared hosting?

I would like to run a time consuming script (to update a database from a 3rd party API) at regular intervals. I was wondering what the best practice for this would be:
What should the 'script' be - an ASP.NET service? Bearing in mind I am on shared hosting, this may not be possible (but I would like to know).
How could the script be scheduled to run at regular intervals/at set time automatically?
Thanks in advance!
Some options for this:
Use a separate thread that keeps running all the time - and does the update on time (and then sleeps).
Use a timer and trigger the update event.
Use a Cache expiration trigger, but test this so that it keeps running without users visiting the site.
I would suggest checking out http://www.beansoftware.com/ASP.NET-Tutorials/Scheduled-Tasks.aspx for more details on these methods.
There is no way you can guarantee that something runs e.g. every night in a normal IIS setup. Batch jobs are thus a pain to handle. The only "mode" of execution for IIS is requests. If your application has no requests it doesn't run at all so IIS does not spend any resources on executing code in your application, i.e. it can unload it entirely.
If you have your own host, you would typically create a windows service to run your background tasks. I believe the same is possible in Azure. But for a standard sharesd IIS host, you basically can't setup a scheduled background task.
One of the simplest hacks is to setup a protected service that executes the job when it gets a request. Then you can make sure an external caller calls into your service at the required intervals.
What you can do is add a System.Timers.Timer in Global.asax.
System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(TimerElapsed), null, new Timespan(0), new Timespan(24, 0, 0));
// This will run every 24 hours.
private void TimerElapsed(object o)
{
// Do stuff.
}
In IISManager, enable HTTP-Keep Alives for your application.
In IIS Manager, select Http Response Headers Module, open it and in the Actions Pane, select Set Common Headers and in there select Enable Http Keep Alives.
Also, check for a setting of your application pool -
Select the application pool of your application, select Advanced Settings from the right Actions Tab.
In there there is a setting called - Idle Timeout (minutes)
By default it is 20 Minutes. Make it something like 60 Minutes or increase it even more and check.

Categories

Resources