I have the web application in visual studio web express and having db in sql server express.
I want to perform insert 100 records on 5:00 PM daily.web application is developed in asp.net MVC and vb.net. and deployed on server machine with IIS 7.5. what logic i should follow?
For me i'm using this approach and it's good till now :)
I've enum with Tasks to do and the time for the task to restart and this time in seconds like this:
public enum ScheduledTasks
{
CleanGameRequests = 120,
AnotherTask = 30,
}
Then i start all my tasks in the Application_Start to ensure that the task will execute while my application is run
protected void Application_Start()
{
...............
// Add the tasks on Application starts
AddTask(ScheduledTasks.CleanGameRequests);
AddTask(ScheduledTasks.AnotherTask);
}
OK now here is the trick :)
in the AddTask method i just add new empty item to cache and set the AbsoluteExpiration for it according to the task time and the call the suitable method for this task.
Actually my i couldn't explain the idea very clear but here is the code:
private static CacheItemRemovedCallback _onCacheRemove;
private void AddTask(ScheduledTasks task)
{
// Add my `CacheItemRemoved` method to be called on cache removed
_onCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);
// Add new key to the cache with the name of this task
// and Expiration time acccordin to the task
HttpRuntime.Cache.Insert(task.ToString(), (int)task, null,
DateTime.Now.AddSeconds((int)task), Cache.NoSlidingExpiration,
CacheItemPriority.NotRemovable, _onCacheRemove);
}
Then all I've to do is to select suitable method for each task in the CacheItemRemoved method :
public void CacheItemRemoved(string key, object time, CacheItemRemovedReason r)
{
//Get Task enum object
var task = (ScheduledTasks)Enum.Parse(typeof(ScheduledTasks), key);
// Select the suitable method to depending on the Task Enum object
switch (task)
{
case ScheduledTasks.CleanGameRequests:
GameRequest.CleanUp();
break;
case ScheduledTasks.AnotherTask:
Service.AnotherTask();
break;
}
// Don't forget to re-add the task to the cache to do it again and again
AddTask(task);
}
Last thing remain for your case is to check the time if it's 5:00 PM and i advice you to put this check in your Service class.
Hope this helped you :)
Since you are using Sql server express edition you can't create scheduled jobs in sql side. But you can try other options like.
Quartz.Net
Service Broker approach
Windows services (If your hosting provider allows)
Related
It looks like previously working approach is deprecated now:
unsupported.dbms.executiontime_limit.enabled=true
unsupported.dbms.executiontime_limit.time=1s
According to the documentation new variables are responsible for timeouts handling:
dbms.transaction.timeout
dbms.transaction_timeout
At the same time the new variables look related to the transactions.
The new timeout variables look not working. They were set in the neo4j.conf as follows:
dbms.transaction_timeout=5s
dbms.transaction.timeout=5s
Slow cypher query isn't terminated.
Then the Neo4j plugin was added to model a slow query with transaction:
#Procedure("test.slowQuery")
public Stream<Res> slowQuery(#Name("delay") Number Delay )
{
ArrayList<Res> res = new ArrayList<>();
try ( Transaction tx = db.beginTx() ){
Thread.sleep(Delay.intValue(), 0);
tx.success();
} catch (Exception e) {
System.out.println(e);
}
return res.stream();
}
The function served by the plugin is executed with neoism Golang package. And the timeout isn't triggered as well.
The timeout is only honored if your procedure code invokes either operations on the graph like reading nodes and rels or explicitly checks if the current transaction is marked as terminate.
For the later, see https://github.com/neo4j-contrib/neo4j-apoc-procedures/blob/master/src/main/java/apoc/util/Utils.java#L41-L51 as example.
According to the documentation the transaction guard is interested in orphaned transactions only.
The server guards against orphaned transactions by using a timeout. If there are no requests for a given transaction within the timeout period, the server will roll it back. You can configure the timeout in the server configuration, by setting dbms.transaction_timeout to the number of seconds before timeout. The default timeout is 60 seconds.
I've not found a way how to trigger timeout for a query which isn't orphaned with a native functionality.
#StefanArmbruster pointed a good direction. The timeout triggering functionality can be got with creating a wrapper function in Neo4j plugin like it is made in apoc.
I know how to get the Execution Id and Instance Id of a job using the Job Context. But if i restart a job, is there way to know if the job execution is the first execution or a restart within the job, for instance inside the reader?
No, but there is an open issue asking for that:
https://java.net/bugzilla/show_bug.cgi?id=7473
This is a bit overly complicated (as the other answer noted, there's an issue opened to consider enhancement for the future Batch 1.1).
You could do this:
//
// Assumes JobContext injected into 'jobCtx' field
//
private boolean isRestart() {
JobOperator jo = BatchRuntime.getJobOperator();
JobInstance jobInstance = jo.getJobInstance(jobCtx.getExecutionId());
int numExecutions = jo.getJobExecutions(jobInstance).size();
return numExecutions > 1;
}
I have custom codeactivities in TFS Build. One of them is a background thread that TFS Build does not know about.
I want to find out if there is a way for this thread to check if a "stop build" has been requested. (i.e. check on the current build status WITHOUT needing a CodeActivityContext)
(NB: I can't use the AsyncCodeActivity (and its cancel mechanism) because this still blocks subsequent tasks)
I am currently using a heartbeat system and relying on a timeout of the heatbeat from the TFS Build flow loop but this is not fool proof.
IBuildDetail.BuildFinished exists but there is the catch 22 of if the build is finished, how do you get iBuildDetail?
Because code activities are "stateless", then using a previous "CodeActivityContext" to get iBuildDetail does not work, i.e. the context no longer exists.
I can get to a code path of _buildServer.GetBuild(_buildUri)
but can't find out how to establish your current builduri (not to be confused with build definition, server, agent or number)
Thanks
Good news, I found a solution
I was caught up in the BuildUri term, it turns out at the bottom of iBuildDetails, is "Uri"
This turns out to be the BuildUri
Thus code like this works ...
static private Uri _buildUri;
static private IBuildServer _buildServer;
...
protected override void Execute(CodeActivityContext context)
{
// Obtain the runtime value of the Text input argument
string ScriptPath = context.GetValue(this.InScriptPath);
_thisContext = context;
IBuildDetail buildDetail = _thisContext.GetExtension<IBuildDetail>();
_buildUri = buildDetail.Uri; // This is the complete string
_buildServer = buildDetail.BuildServer;
......
In background tthread
try
{
IBuildDetail buildDetail = _buildServer.GetBuild(_buildUri); // this does not work as it is not the BuildUri
if (buildDetail != null)
{
if (buildDetail.Status == BuildStatus.Stopped)
{
TerminateProcess();
}
}
}
catch (Exception Ex)
{
TerminateProcess();
}
I got a ASP.NET MVC 4 web application and quartz.net running as a windows service and common logging configured according to these sources :
http://geekswithblogs.net/TarunArora/archive/2012/11/16/install-quartz.net-as-a-windows-service-and-test-installation.aspx
http://geekswithblogs.net/TarunArora/archive/2012/11/17/quartz.net-windows-service-configure-logging.aspx
and with this code in Global.asax in place:
var properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "ServerScheduler";
// set thread pool info
properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
properties["quartz.threadPool.threadCount"] = "5";
properties["quartz.threadPool.threadPriority"] = "Normal";
// set remoting expoter
properties["quartz.scheduler.proxy"] = "true";
properties["quartz.scheduler.proxy.address"] = "tcp://localhost:555/QuartzScheduler";
// construct a scheduler factory
ISchedulerFactory schedFact = new StdSchedulerFactory(properties);
// get a scheduler
IScheduler sched = schedFact.GetScheduler();
sched.Start();
IJobDetail jobDetail = JobBuilder.Create<SimpleJob>()
.WithIdentity("simpleJob", "simpleJobs")
.RequestRecovery()
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("simpleTrigger", "simpleTriggers")
.StartNow()
.WithSimpleSchedule(x => x.WithRepeatCount(4).WithIntervalInSeconds(10))
.Build();
sched.ScheduleJob(jobDetail, trigger);
and the job:
public class SimpleJob : IJob
{
public SimpleJob()
{
}
public void Execute(IJobExecutionContext context)
{
Debug.WriteLine("I Executed at " + DateTime.Now.ToString());
}
}
and now if I run the app the log produces something like this 5 times
19:35:23 [ServerScheduler_QuartzSchedulerThread] DEBUG Quartz.Core.QuartzSchedulerThread - Batch acquisition of 1 triggers
19:35:23 [ServerScheduler_QuartzSchedulerThread] DEBUG Quartz.Simpl.SimpleJobFactory - Producing instance of Job 'simpleJobs.simpleJob', class=Navigate.Quartz.Jobs.SimpleJob
19:35:23 [ServerScheduler_QuartzSchedulerThread] DEBUG Quartz.Core.QuartzSchedulerThread - Batch acquisition of 1 triggers
19:35:23 [ServerScheduler_Worker-1] DEBUG Quartz.Core.JobRunShell - Calling Execute on job simpleJobs.simpleJob
19:35:23 [ServerScheduler_Worker-1] DEBUG Quartz.Core.JobRunShell - Trigger instruction : NoInstruction
Then deletes the trigger and carries on, but no job is executed and no lines are written to debug output
if I run the scheduler embedded in the app, however, by not passing the NameValueCollection to the StdSchedulerFactory
ISchedulerFactory schedFact = new StdSchedulerFactory();
everything works fine and I get the lines outputted 5 times every 10 seconds
I Executed at 28.05.2013. 19:47:48
I Executed at 28.05.2013. 19:47:58
I Executed at 28.05.2013. 19:48:08
I Executed at 28.05.2013. 19:48:18
I Executed at 28.05.2013. 19:48:28
What am I missing, why isnt the windows service actually executing the code, the service is running as Local System, nothing changes if I change it to administrator account tho. Any help will be appreciated.
Chris
I think that the service may actually be executing the code but you are not seeing the output. Try changing the Debug.WriteLine() to use Common.Logging so that the output is included in the same log that Quartz is using for its log output. For code examples see http://netcommon.sourceforge.net/docs/1.2.0/reference/html/logging.html.
I also looked at the code that we are using in our implementation, and I see that we are not doing a .Start() after .GetScheduler(). Since you are working with a service running Quartz, the scheduler should already be started, and you should just work with the scheduler that is returned from .GetScheduler(). Try removing the .Start() from your code.
I have followed this post to build a scheduled task at the end of each month
Scheduled tasks using Orchard CMS
private void ScheduleNextTask(DateTime date)
{
if (date > DateTime.UtcNow)
{
var tasks = _taskManager.GetTasks(TaskType);
if (tasks == null || tasks.Count() == 0)
_taskManager.CreateTask(TaskType, date, null);
}
}
This works fine in orchard 1.4, but when I upgraded to 1.5.1, It thorws an error everytime I enable/disable module, change themes, or edit source code while debugging. This is the error
Cannot access a disposed object.Object name: 'TransactionScope'
If I comment all the lines access to _taskManager in method ScheduleNextTask, no more error. I don't know why but I need the task running, so anyone can give me an advice?