EverNote android-job: How can I run a job at a specific time once a day every week? - evernote

I'm developing a weekly scheduler in android and I'm interesting in a periodic job (once a week for example) that is fired at a specific time (for example at 4.00 PM) with evernote android-job
I have read this post
https://github.com/evernote/android-job/blob/master/FAQ.md#how-can-i-run-a-job-at-a-specific-time-once-a-day
and I can run a job every day once a day, but it is not my case.
If I set
new JobRequest.Builder( MY_TAG )
.setExact( TimeUnit.HOURS.toMillis( 16 ) + TimeUnit.MINUTES.toMillis( 0 ))
.setPeriodic( TimeUnit.DAYS.toMillis( 7 ), TimeUnit.MINUTES.toMillis(5) )
.setPersisted(true)
.build()
.schedule();
I have this error
"Can't call setExact() on a periodic job"
Can someone help me?

setExact() and setPeriodic() are two distinct features,they cannot be coupled.
If you want to use setExact periodically, You'd have to programatically schedule a job again once the previously set job has run.

try this dude.
public final class MyDailyJob extends DailyJob {
public static final String TAG = "MyDailyJob";
public static void schedule() {
// schedule between 1 and 6 AM
DailyJob.schedule(new JobRequest.Builder(TAG), TimeUnit.HOURS.toMillis(1), TimeUnit.HOURS.toMillis(6));
}
#NonNull
#Override
protected DailyJobResult onRunDailyJob(Params params) {
return DailyJobResult.SUCCESS;
}
}
reference link

Related

How to set a Job Due Date in Activiti 5.22.0?

I got a reference to a Job object like this:
Job timer = managementService.createJobQuery().processInstanceId(execution.getParentId()).singleResult();
Could anyone please tell me how can I set the timer due date to an arbitrary
date or time period in Activiti 5.22.0?
I could not find a suitable method in ManagementService or Job class.
Best regards.
For me, I found only one way to do this:
Create a new timer and set config from the old one.
This is a piece example of how I did this, do not forget to fix it, to avoid NPE
TimerEntity oldTimer = (TimerEntity) managementService.createJobQuery()
.processInstanceId("YOUR_PROCESS_INSTANCE_ID")
.timers()
.singleResult();
commandExecutor.execute(new Command<Void>() {
#Override
public Void execute(CommandContext commandContext) {
oldTimer.delete();
TimerEntity newTimer = new TimerEntity();
newTimer.setJobHandlerConfiguration(oldTimer.getJobHandlerConfiguration());
newTimer.setJobHandlerType(oldTimer.getJobHandlerType());
newTimer.setExclusive(oldTimer.isExclusive());
newTimer.setRepeat(oldTimer.getRepeat());
newTimer.setRetries(oldTimer.getRetries());
newTimer.setEndDate(oldTimer.getEndDate());
newTimer.setExecutionId(oldTimer.getExecutionId());
newTimer.setProcessInstanceId(oldTimer.getProcessInstanceId());
newTimer.setProcessDefinitionId(oldTimer.getProcessDefinitionId());
newTimer.setTenantId(oldTimer.getTenantId());
// Sets a new date
newTimer.setDuedate(new Date());
commandContext.getJobEntityManager().schedule(newTimer);
return null;
}
});

In Unity is a WWW class asynchronous or synchronous?

I am trying to understand how to write a WWW call in Unity. According to the description here http://docs.unity3d.com/ScriptReference/WWW.html I can inspect the isDone property, but in the example on the same page, it makes no attempt to inspect isDone.
The question I have is, if I make a WWW call and it takes several seconds to reply, doesn't the game freeze?
I would like to think the right code is this, but is it?
StartCoroutine(WaitForResponse(myWWWObject));
private IEnumerator WaitForResponse(WWW aRequest ) {
while ( ! aRequest.isDone )
yield return aRequest;
}
Does the game freeze until aRequest is done? Or is it truly asynchronous?
You need to understand Coroutines - a fundamental feature of Unity that allows you to write long-duration code functions (eg: longer then a frame) that will not freeze your game.
http://docs.unity3d.com/Manual/Coroutines.html
In C# you can spot a coroutine function because it has a return type of IEnumerator. And you can spot the locations in the code where the function will suspend and continue from again by the C# keyword yield.
Each MonoBehaviour class can manage coroutines, and if you tell it to start one with StartCoroutine(), then MonoBehaviour will call the coroutine every frame (sometimes more then once) until the Coroutine reaches the end.
For WWW class (which supports co-routines), all you need is to call this:
WWW www = new WWW(url);
yield return www;
You create a WWW class with the URL to retrievve, and the yield will basically be called each frame automatically by the MonoDevelop coroutine manager until www object says it has completed (successfully or failure).
Your game will not freeze at all during this time.
In the linked documentation page for WWW, the following method is a coroutine method:
IEnumerator Start() {
WWW www = new WWW(url);
yield return www;
Renderer renderer = GetComponent<Renderer>();
renderer.material.mainTexture = www.texture;
}
The yield statement is used to pause execution and return control to Unity and then to resume execution in the next game frame. For example yield return null; will cause execution to resume in the next frame. Additionally, you can extend that behaviour by using one of the classes that derive from YieldInstruction class, for example WaitForSeconds.
Consider yield return new WaitForSeconds(1f); - this will resume execution after 1 second of game time has passed. The WWW class works in similar way. You can use an instance of that class to yield execution, returning only after the download has been completed, no need to manually poll the isDone property.
Keep in mind that you can only yield in Coroutines, I advise you read up on them. If you want to do a WWW request not in a Coroutine then you have to poll the isDone manually and proceed when completed.
To answer last question: Will the game freeze when creating an instance of the WWW class? - No. The class works asynchronously. You can use it in normal Update/Start etc. functions and inside Coroutines with yield.
if I make a WWW call and it takes several seconds to reply, doesn't the game freeze?
Not, Game Will not be freez try this code and you will see that log "after corou" will show immediately even the picture is downloading.
public class WWWDemo : MonoBehaviour {
bool b = true;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update()
{
if (b) {
StartCoroutine(ExampleCoroutine());
Debug.LogWarning("after corou");
}
}
IEnumerator ExampleCoroutine()
{
b = false;
Debug.Log("Time : " + DateTime.Now);
string url = "http://images.earthcam.com/ec_metros/ourcams/fridays.jpg";
WWW www = new WWW(url);
yield return www;
Debug.Log("Time : " + DateTime.Now);
Renderer render = gameObject.GetComponent<Renderer>();
render.material.mainTexture = www.texture;
Debug.Log("Time : " + DateTime.Now);
}
}
but the execution of next line will definitely stop after yield return www statement it will wait unitl the picture download while the rest events of Unity will execute async.
Consider below example as well separately. Start Event executes ones it will wait but update will run continuously.
IEnumerator Start() {
Debug.Log("Time : " + DateTime.Now);
string url = "http://images.earthcam.com/ec_metros/ourcams/fridays.jpg";
WWW www = new WWW(url);
yield return www;
Debug.Log("Time : " + DateTime.Now);
Renderer render = gameObject.GetComponent<Renderer>();
render.material.mainTexture = www.texture;
Debug.Log("Time : " + DateTime.Now);
}
void Update()
{
Debug.Log("update is running while start is waiting for downloading");
}

Unity Time for calculating session length

Is there a way of registering time when you exit a Unity application (i.e. you press play and stop the app) or perhaps when you exit a standalone build?
Using the following simple line of code, I can write to the console when my start button was pressed, so I wonder if I could do the same when the app is quit, so that the difference would be the length of the session?
Debug.Log("Start Button pressed # " + DateTime.Now);
At the End of Application you can Save your Session Time. And In Start Method you can Load it From PlayerPrefsto use it.
Like This :
void OnApplicationQuit()
{
DateTime time = new DateTime();
time.AddSeconds(Time.realtimeSinceStartup);
PlayerPrefs.SetString("SessionTime",time.ToBinary().ToString());
}
void Start()
{
DateTime time = new DateTime();
string timeString = PlayerPrefs.SetString("SessionTime","");
if(timeString != "")
{
Convert.ToInt64(timeString);
time = DateTime.FromBinary(time);
Debug.Log("Previous Session Time : " + time.ToString());
}
}
You can also achieve this by using System.DateTime.Now and storing it in some variable at start. and getting Session Time at End by subtracting saved time from System.DateTime.Now. I hope its Helpful :)
You can use Time.realtimeSinceStartup to get the number of seconds since the application was start. Furthermore, OnApplicationQuit will be called (on any MonoBehaviour that implements it) when the application is closed. I am not completely sure it works in the editor but I think it would.
void OnApplicationQuit() {
Debug.Log(Time.realtimeSinceStartup);
}
I hope that helps!

Loading any persistent workflow containing delay activity when it is a runnable instance in the store

We are trying to load and resume workflows which have a delay. I have seen the Microsoft sample of Absolute Delay for this using store.WaitForEvents and LoadRunnableInstance to load the workflow. However here the workflow is already known.
In our case we want to have an event waiting for the store.WaitForEvents after every say 5 seconds to check if there is a runnable instance and if so only load and run that /those particular instances. Is there a way I could know which workflow instance is ready.
We are maintaing the workflow id and the xaml associated to it in our database, so if we could know the workflow instance id we could get the xaml mapped to it, create the workflow and then do a LOadRunnableInstance on it.
Any help would be greatly appreciated.
Microsoft sample (Absolute Delay)
public void Run(){
wfHostTypeName = XName.Get("Version" + Guid.NewGuid().ToString(),
typeof(WorkflowWithDelay).FullName);
this.instanceStore = SetupSqlpersistenceStore();
this.instanceHandle =
CreateInstanceStoreOwnerHandle(instanceStore, wfHostTypeName);
WorkflowApplication wfApp = CreateWorkflowApp();
wfApp.Run();
while (true)
{
this.waitHandler.WaitOne();
if (completed)
{
break;
}
WaitForRunnableInstance(this.instanceHandle);
wfApp = CreateWorkflowApp();
try
{
wfApp.LoadRunnableInstance();
waitHandler.Reset();
wfApp.Run();
}
catch (InstanceNotReadyException)
{
Console.WriteLine("Handled expected InstanceNotReadyException, retrying...");
}
}
Console.WriteLine("workflow completed.");
}
public void WaitForRunnableInstance(InstanceHandle handle)
{
var events=instanceStore.WaitForEvents(handle, TimeSpan.MaxValue);
bool foundRunnable = false;
foreach (var persistenceEvent in events)
{
if (persistenceEvent.Equals(HasRunnableWorkflowEvent.Value))
{
foundRunnable = true;
break;
}
}
if (!foundRunnable) {
Console.WriteLine("no runnable instance");
}
}
Thanks
Anamika
I had a similar problem with durable delay activities and WorkflowApplicationHost. Ended up creating my own 'Delay' activity that worked essentially the same way as the one out of the box, (takes an arg that describes when to resume the workflow, and then bookmarks itself). Instead of saving delay info in the SqlInstanceStore though, my Delay Activity created a record in a seperate db. (similar to the one you are using to track the Workflow Ids and Xaml). I then wrote a simple service that polled that DB for expired delays and initiated a resume of the necessary workflow.
Oh, and the Delay activity deleted it's record from that DB on bookmark resume.
HTH
I'd suggest having a separate SqlPersistenceStore for each workflow definition you're hosting.

ASP.Net WebForms running mulitple queries at the same time

This is for an enterprise web application.
We are building a front page/dashboard that queries our database for live statistics. The page has 3 update panels, each update panel has a user control that pulls data for it's box. Lets call the user controls UC_NotStarted, UC_Active and UC_Finished.
We have built the queries that return the data and all of them take a while to run (~7 seconds each). So if we let the first page run with one update panel the image spins for ~21 seconds and display everything. We have broken that code into 3 update panels and set the loading to conditional. When we do this we get one box to load every 7 seconds. That’s a step in the right direction but they load sequentially (UC_NotStarted is queried waits 7 seconds and displays, then UC_Active goes for 7 seconds, and finally UC_Finished runs for 7 seconds). We are still at 21 seconds but data is being shown every 7 seconds.
We would like all of the data to be shown in 7 seconds since all of the update panels should be fetching the data at the same time. Instead of using LinqToSQL to pull the data I am now leaning towards web services to get it but not sure if that will work.
Look at the ThreadPool, specifically the QueueUserWorkItem method. It's quite possible with this to run the 3 queries simultaneously and sit in a Thread.Sleep loop waiting for all three to finish executing so you can update all relevant parts of the page.
The following code will almost certainly require tweaking but would give you a rough idea of how to do this:
public class QueryResult
{
public bool Completed;
public DataTable Result;
public int ResultId;
}
public void GetData()
{
var QueryResults = new List<QueryResult>();
queryResults.Add(new QueryResult() { ResultId = 1 });
queryResults.Add(new QueryResult() { ResultId = 2 });
queryResults.Add(new QueryResult() { ResultId = 3 });
ThreadPool.QueueUserWorkItem(new WaitCallback(QueryRoutine), queryResults[0]);
ThreadPool.QueueUserWorkItem(new WaitCallback(QueryRoutine), queryResults[1]);
ThreadPool.QueueUserWorkItem(new WaitCallback(QueryRoutine), queryResults[2]);
var completedResults = new List<QueryResult>();
while(QueryResults.Count > 0)
{
for(int 1 = QueryResults.Count - 1; i >= 0; i--;)
{
if (queryResults[i].Completed)
{
completedResults.Add(queryResults[i]);
queryResults.RemoveAt(i);
}
}
Thread.Sleep(500);
}
// All background threads have completed, do something with the results,
// return them to the front-end, etc,..
}
public void QueryRoutine(object qR)
{
var queryResult = (QueryResult)qR;
// perform long running query here on a distinct thread, as QueryRoutine
// is now being run on three separate threads by the calls to QueueUserWorkItem
// based on queryResult.ResultId picking the relevant query for values
// of 1, 2 or 3
queryResult.Completed = true;
}

Resources