how can i run time in my java application without threads? - java.util.date

I want to get current time to my java app and want to make time running.If i use thread class my app is getting slower and slower. How can i aware this? Is there any method of running time?
Here is my code:-
new Thread(new Runnable() {
#Override
public void run() {
while (true) {
String s=new Date().toString();
String tim=s.split(" ")[3];
}
}
}).start();

Related

How to send constantly updates using .Net Core SignalR?

I am new to SignalR and I would like to build such app -- every second a hub sends current time to all connected clients.
I found tutorial, but it is for .Net Framework (not Core): https://learn.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-high-frequency-realtime-with-signalr So on one hand I don't know how to translate it to .Net Core SignalR, on the other hand I don't know how to write it from scratch (the limiting condition is the fact a hub is a volatile entity, so I cannot have state in it).
I need something static (I guess) with state -- let's say Broadcaster, when I create some cyclic action which in turn will send updates to clients. If such approach is OK, how to initialize this Broadcaster?
Currently I added such static class:
public static class CrazyBroadcaster
{
public static void Initialize(IServiceProvider serviceProvider)
{
var scope = serviceProvider.CreateScope();
var hub = scope.ServiceProvider.GetRequiredService<IHubContext<ChatHub>>();
var sub = Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe(_ => hub.Clients.All.SendAsync("Bar", DateTimeOffset.UtcNow));
}
}
Yes, I know it is leaky. I call this method at the end of Startup.Configure, probably tons of violations here, but so far it is my best shot.
The missing piece was hosted service, i.e. the code that runs in the background -- https://learn.microsoft.com/en-US/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.2.
So my crazy class is now transformed into:
public sealed class HostedBroadcaster : IHostedService, IDisposable
{
private readonly IHubContext<ChatHub> hubContext;
private IDisposable subscription;
public HostedBroadcaster(IHubContext<ChatHub> hubContext)
{
this.hubContext = hubContext;
}
public void Dispose()
{
this.subscription?.Dispose();
}
public Task StartAsync(CancellationToken cancellationToken)
{
this.subscription = Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe(_ => hubContext.Clients.All.SendAsync("Bar", DateTimeOffset.UtcNow));
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
this.subscription?.Dispose();
return Task.CompletedTask;
}
}

How to create custom native module android for react native app?

I've build simple service in android studio to run a service every second in console log,
and I want to implement my android studio code in react native
there's a way to do that?
let say I've a code :
myService.class
public class myService extends Service {
private Handler handler= new Handler();
private boolean run = true;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onStart(Intent i, int startId){
super.onStart(i, startId);
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (run){
Log.e("Second", "test");
}
handler.postDelayed(this,1000);
}
},1000);
}
public void onDestroy(){
super.onDestroy();
run=false;
Log.d("Test", "Screen on");
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onPause() {
super.onPause();
Log.d("Test", "Screen off");
startService(new Intent(this, myService.class));
}
#Override
protected void onResume() {
super.onResume();
startService(new Intent(this, myService.class));
}
}
You can use RN Native modules. For background tasks Headless JS is useful. And for listening events LifecycleEventListener is what you are looking for. getReactApplicationContext().startService(new Intent(getReactApplicationContext(), myService.class) will do the rest. I am ready for further help
Please refer to https://facebook.github.io/react-native/docs/native-modules-android
You can follow the docs: https://facebook.github.io/react-native/docs/native-modules-android
The other answer pretty much covers the way you implement RN Modules. A useful tip is how to send events to JavaScript, such as below:
private void sendEvent(ReactContext reactContext,
String eventName,
#Nullable WritableMap params) {
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
...
WritableMap params = Arguments.createMap();
...
sendEvent(reactContext, "keyboardWillShow", params);
Further Reading (for your intended feature) for background tasks [ANDROID]
Just to add, you seem like you want to create a background task in React Native. Now from experience, if you want to run something every second - this will work as expected, until the device goes into Doze mode. If you don't want the service to run in the background or Doze mode - that's fine. If so, you may want to start reading about Doze mode and how to test your service in a Doze mode environment.
The issue with background tasks, is that if the phone is idle or stationary - the phone will go into Doze mode. This impacts upon some functionality, such as network. It is expected that if you need to perform actions in Doze mode that you do within a Maintenance Window
Now, I've managed to overcome some issues - by using an Alarm Clock Manager and resetting it to stop Doze mode. However, this does not work in all cases. You'll need a combination of that and a service to keep it alive (but will act differently on a lot of phones). Sometimes the GC just ditches it and kills the process.
Useful links:
Testing your service in Doze mode:
https://developer.android.com/training/monitoring-device-state/doze-standby#testing_doze
Understanding Doze:
https://developer.android.com/training/monitoring-device-state/doze-standby#understand_doze

Realtime checking the progress monitor using Job.getJobManager.IsIdle()

I am trying to continuously check if the progress monitor has an operation that is running in the background.
For this, I used Job.getJobManager.IsIdle().
I have tried the following:
Put it inside a Job.
WorkspaceJob job = new WorkspaceJob("Hello")
{
#Override
public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException
{
while(!Job.getJobManager().isIdle())
{
System.out.println(!Job.getJobManager().isIdle());
}
return Status.OK_STATUS;
}
};
job.setPriority(Job.SHORT);
job.schedule();
But this does not work as Job.getJobManager.isIdle will never return false because Job 'Hello' is running.
Put it inside an asynchronous thread.
new Thread(new Runnable()
{
#Override
public void run()
{
Display.getDefault().asyncExec(new Runnable()
{
#Override
public void run()
{
while(!Job.getJobManager().isIdle())
{
System.out.println("hi");
}
}
});
}
}).start();
But this does not work either as this will freeze the main Eclipse GUI preventing other processes (if there are any existing) to finish.
If anyone has suggestions or any input on how it should be done, it would be great!
You can use a job change listener IJobChangeListener to listen for all changes to job states. You can than test for idle in appropriate places in the listener. Do not try and loop calling isIdle.
You can use the JobChangeAdapter class which provides default implementations of the IJobChangeListener methods so that you only have to override the events you are interested in, probably just the done method:
Job.getJobManager().addJobChangeListener(new JobChangeAdapter()
{
#Override
public void done(IJobChangeEvent event)
{
if (Job.getJobManager().isIdle() {
// Manager is idle
}
}
});

Eclipse Plugin - execute when user changes window in perspective

I would like to ask how would you automatically execute a plugin when a user switches windows in the perspective.
Can this be done maybe with startup handler and IWorkbench?
You can use IPartListener to listen to changes in which part is active.
You can set this up in using IStartup but you need to do this using something like this:
public class StartUp implements IStartup
{
#Override
public void earlyStartup()
{
IWorkbench workbench = PlatformUI.getWorkbench();
workbench.getDisplay().asyncExec(new Runnable() {
#Override
public void run() {
IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
if (window != null) {
window.getPartService().addPartListener(your part listener);
}
}
});
}
}
This is using Display.asyncExec to delay setting up the part listener until after the startup has completed as the workbench window will not be available when earlyStartup runs.

unexpected async await behavior in mstest unit test

I'm having newbie problems testing an async method. I've read a few other posts, including How to correct write test with async methods?, and I think I'm doing things correctly, but I'm clearly missing something.
Here's the code I'm trying to test:
/// <summary>
/// Temporary method used to simulate the time required to generate a report.
/// </summary>
public virtual async Task GenerateTestReportAsync()
{
++ActiveTaskCounter;
await Task.Delay(2000);
--ActiveTaskCounter;
}
And here's the test (yes, I could/should improve it by storing the ActiveTaskCounter values in a list, but that's beside the point):
[TestMethod]
public async Task GenerateTestReportAsyncUpdatesActiveTaskCounter()
var bayViewModel = CreateBayViewModel();
var invocationCount = 0;
bayViewModel.PropertyChanged += (sender, args) =>
{
if (args.PropertyName == "ActiveTaskCounter")
{
++invocationCount;
}
};
await bayViewModel.GenerateTestReportAsync();
//Thread.Sleep(2100); // TODO: Why is this needed?
Assert.AreEqual(2, invocationCount);
Assert.AreEqual(0, bayViewModel.ActiveTaskCounter);
}
The test always passes with the Thread.Sleep uncommented. It always fails with the Thread.Sleep commented, as shown above. Why is this? I assumed the code below the "await bayViewModel.GenerateTestReportAsync()" wouldn't even execute until GenerateTestReportAsync was really finished.
BTW, I'm using:
Microsoft Visual Studio Ultimate 2012
Version 11.0.51106.01 Update 1
Microsoft .NET Framework
Version 4.5.50709
Thanks for any help you can provide! This has me stumped :-|
EDIT: Here's a minimal repro of the view model class...
using System.ComponentModel;
using System.Threading.Tasks;
public class BayViewModel : INotifyPropertyChanged
{
public BayViewModel()
{
PropertyChanged = (sender, args) => { };
}
public event PropertyChangedEventHandler PropertyChanged;
private int _activeTaskCounter;
public int ActiveTaskCounter
{
get
{
return _activeTaskCounter;
}
set
{
_activeTaskCounter = value;
PropertyChanged(this, new PropertyChangedEventArgs("ActiveTaskCounter"));
}
}
public virtual async Task GenerateTestReportAsync()
{
++ActiveTaskCounter;
await Task.Delay(2000);
--ActiveTaskCounter;
}
}