How to call specific method on every 10th second? - java

I want to call a method on every 5th second,
I used a timer, but I don't know how to use it properly.
I have a method in one CountryDTO class as below.
public MoviesDTO getMovieDTOByName(String movieName) {
Session session = factory.openSession();
String hql = "FROM MoviesDTO WHERE name=:nm";
Query query = session.createQuery(hql);
query.setParameter("nm", movieName);
return (MoviesDTO) query.uniqueResult();
}
And I call it from the main method.as below:
public static void main(String[] args) {
Timer timer = new Timer();
CountryDAO countryDAO = new CountryDAO();
timer.schedule(countryDAO.getMovieDTOByName("Rabgo"), 5000);
}
But, I'm getting this below exception:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method schedule(TimerTask, long) in the type Timer is not applicable for the arguments (MoviesDTO, int)

Using Timer is not a good idea.Using ScheduledThreadPoolExecutor instead if you use jdk 1.5 or later.
doc: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html
reason:
Java Timer vs ExecutorService?

You have a compilation error as the log says. The method schedule takes 2 arguments (TimerTask, long) instead of (MoviesDTO, int) that you have provided.
Take a look at How to set a timer in Java (mentioned by Masked Man in the comment on your post) to get the solution

There are plenty third party jar(s) like Quartz scheduler available for java. This kind of jar(s) internally handle all the required scheduling process for us and we can focus on our business logic of scheduler.
Quartz is basically made for handling complex schedule in the Java.
You must have knowledge of cronjob in this case.
You can also refer CronMaker.
(Note:- This is just suggestion for you. If your scheduling process is taking to-much time to handle it and you are diverting from your use-case then you can go further with this suggestion.)

Related

Finding caller method from a Spring service

Summarize
Goal
I have an application that is written in Java using the Spring framework. There is a service that is being used as the handler for grabbing and releasing locks in the database (InnoDB). My goal is to be able to log the grabbing and releasing of the locks to create a lock history. For each lock interaction, I would like to know not only the name of the lock involved, but also where this request is coming from in the code (if possible, class name, method name, and line number).
My expected database entry will look something like this:
id
lock_name
clazz
method
line
lock_date
unlock_date
unlock_type
0
tb_member
MemberTools
createMember
123
2021-12-23 10:16:00
2021-12-23 10:16:01
COMMIT
1
tb_member
MemberTools
editMember
234
2021-12-23 10:16:01
2021-12-23 10:16:02
COMMIT
I would like to know if there is an easy way to obtain this given that I am using the Spring framework.
Describe
So far, I have tried two things:
Forcing the caller to pass a reference to itself or its current StackTraceElement (using Thread.currentThread().getStackTrace()[1]). This is not only extremely repetitive, but it also is prone to human error, as a developer might not realize that they need to pass in some reference to themselves.
Inside of the lock service, use the getStackTrace method and walk through the elements to find the "correct" one. This is made very hard by Spring and the fact that before a call actually reaches the inside of a class with the #Service annotation, the call stack is muddled by numbers of calls between proxies and generated classes and such. Unless there is a deterministic way to find the number of calls in between the Service and the caller, then this doesn't seem like a good way either.
I have referenced this stack overflow question while working, but these do not take into account the usage of the Spring framework.
Show
A reproducible example will look something like this. First, the structure:
root\
LockService.java
getLock()
MemberTools.java
createMember()
LockService.java:
#Service
public class LockService {
#Transactional
public Lock getLock(String key) {
Lock searchLock = new Lock();
searchLock.setKey(key);
lockMapper.getLock(searchLock);
LockHistory lockHistory = new LockHistory();
// Fill out lockHistory object...
lockMapper.markAsLocked(lockHistory);
attachTransactionCompletedListener(lockHistory);
}
private void attachTransactionCompletedListener(LockHistory lockHistory) {
/* Attach a listener onto the current spring transaction so that we
* can update the database entry when the transaction finishes and
* the lock is released.
*/
}
}
MemberTools.java:
public class MemberTools {
#Autowired
LockService lockService;
#Transactional(propagation = Propagation.REQUIRES_NEW)
public void createMember() {
lockService.getLock("tb_member");
/* Do create member stuff...
* When this returns, the lock will be released
* (either from COMMIT, ROLLBACK, or UNKNOWN Spring error)
*/
}
}
By the time the getLock() method is reached, the stack trace is muddled with many calls that Spring inserts (proxies, reflections, etc.). Putting a breakpoint in this function and examining Thread.currentThread().getStackTrace() will show this.

Schedule at 24hrs interval

I want to know the best method to schedule a code. I have a code that generates reports and sends mail to a set of people at interval of 24hrs. Its a console based java application. I want to know the best method to schedule that. Sometimes I may need to change that to 12hrs interval. However the application doesn't perform any other task in between the interval.
Here are few approach, from simplest to most comprehensive:
sleep():
TimeUnit.HOURS.sleep(24)
This approach is very simple, do the work and sleep for 24 hours. Actually it is a bit more complex because the report generation takes some time, so you have to sleep slightly shorter. All solutions below handle this transparently.
java.util.Timer#scheduleAtFixedRate() - simple, built-in Java solution.
#Scheduled annotation in spring or #Schedule in ejb - more complex but also more powerful, e.g. accepts cron expressions:
#Scheduled(fixedRate=DateUtils.MILLIS_PER_DAY)
public void generateReport() {
//...
}
quartz-scheduler - full blown Java scheduler with clustering and fail-over, misfire handling, full cron support, etc. Very comprehensive:
newTrigger().
withSchedule(
simpleSchedule().
withIntervalInHours(24).
repeatForever()
).build();
or
newTrigger().
withSchedule(
cronSchedule().
dailyAtHourAndMinute(17, 30). //17:30
).build();
I am using two ways:
First for non managed code like client code:
Chron4J
Second is implmented in the JavaEE framewoks. You can use it via annotating methods when you use an container like Glassfish/JBoss. Would be something like this:
#Schedule(second="*/1", minute="*",hour="*", persistent=false)
public void doWork(){
System.out.println("timer: " + helloService.sayHello());
}
I would take a look at the quartz scheduler if I were you.
I used in a number of applications and it's really easy to use.
You can find more information here: http://quartz-scheduler.org/
If you use the spring stack I would surely recommend it, since it is super easy to configure in xml and let spring inject all the stuff for you.
Well, if the program can be idle try something like this
try
{
for (;;) {
//code
Thread.sleep(1000 * 60 * 60 * 24);
//code
}
}
catch(Exception e)
{
System.out.println(e);
}

how to create a plugin for web application to calculate the each and every invoked method execution time

My application file (EAR) consists of combination of EJB and WAR. FrameWork is JSF and IDE is Netbeans 6.9.1 applition server is glassfich V2.x. I want to calculate the execution time fro each and every invoked method in my application. i have gone through so many blogs. most of them suggested to use AOP. but nobody tell me how to configure and how to use it in my application. could anybody tell me ragarding this. I have some code here and i made use of AOP and JAMon to calculate the method execution time. but i confused about how to configure this because for every method invocation this calss should be invoked for that what to do i dont know. could anybody give some suggestions on it.If you any additional details to answer this i will provide. Code is:
public class PerformanceMonitorIncptr implements MethodInterceptor{
/** Creates a new instance of PerformanceMonitorIncptr */
public PerformanceMonitorIncptr() {
}
public Object invoke(MethodInvocation mi) throws Throwable {
String mName = mi.getMethod().getDeclaringClass().getName() + "." + mi.
getMethod().getName();
Monitor mon = MonitorFactory.start(mName);
// long l = System.currentTimeMillis();
Object returnValue = null;
try {
returnValue = mi.proceed();
} finally {
mon.stop();
System.out.println(mon);
}
System.out.println(mName);
// System.out.println(l - System.currentTimeMillis());
return returnValue;
}
}
AOP is best suited here.
You need to configure #PointCut #Around each method you want to log the time of execution
Have a look at this tutorial .
Update
I hope 20 methods you are talking about /can be are Spring Service methods, and you don't need to alter them at all you just need to configure a #Aspect that will involve all the methods. read more
AOP is the solution.
But why would you write it yourself.
Use Javamelody -> EJB configuration documentation.
We use it with Spring, and it's great. There are also such solutions as AppDynamics, DynaTrace, NewRelic, JXInsight, CorrelSense, Nastel.
As for me Javamelody is free, opensource and very easy to use.

Retry Task Framework

I have a number of situations where I need to retry a task n-times if it fails (sometimes with some form of back-off-before-retry logic). Generally, if an exception is thrown, the task should be retried up to the max-retry count.
I can easily write something to do this fairly generically, but not wanting to re-invent the wheel I was wondering if anyone can recommend any frameworks for this. The only thing I have been able to find is: Ant Retry but I don't want to use Ant tasks directly in my application.
Thanks
Check out Failsafe (which I authored). It's a simple, zero-dependency library for performing retries, and supports synchronous and asynchronous retries, Java 8 integration, event listeners, integration with other async APIs, etc:
RetryPolicy retryPolicy = new RetryPolicy()
.handle(ConnectException.class, SocketException.class);
.withMaxRetries(3);
Connection connection = Failsafe.with(retryPolicy).get(() -> connect());
Doesn't get much easier.
You can use RetriableTasks as outlined in this post: Retrying Operations in Java. You can quite easily change its waiting algorithm if you like.
Sample code:
//creates a task which will retry 3 times with an interval of 5 seconds
RetriableTask r = new RetriableTask(3, 5000, new Callable(){
public Object call() throws Exception{
//put your code here
}
});
r.call();
If you use Spring:
//import the necessary classes
import org.springframework.batch.retry.RetryCallback;
import org.springframework.batch.retry.RetryContext;
import org.springframework.batch.retry.backoff.ExponentialBackOffPolicy;
import org.springframework.batch.retry.policy.SimpleRetryPolicy;
import org.springframework.batch.retry.support.RetryTemplate;
...
// create the retry template
final RetryTemplate template = new RetryTemplate();
template.setRetryPolicy(new SimpleRetryPolicy(5));
final ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
backOffPolicy.setInitialInterval(1000L);
template.setBackOffPolicy(backOffPolicy);
// execute the operation using the retry template
template.execute(new RetryCallback<Remote>() {
#Override
public Remote doWithRetry(final RetryContext context) throws Exception {
return (Remote) Naming.lookup("rmi://somehost:2106/MyApp");
}
});
Original blog post
If you are using Spring, it is very simple using Spring Retry Library.
Now, Spring Retry is an individual library (earlier it was part of Spring Batch) framework.
Step1: Add spring retry dependency.
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
<version>1.1.2.RELEASE</version>
</dependency>
Step2: Add #EnableRetry annotation to your class which contains main() method of your application or into any of your #Configuration class .
Step3: Add #Retryable annotation to your method which you want to retry/call again, in case of exceptions.
#Retryable(maxAttempts=5,backoff = #Backoff(delay = 3000))
public void retrySomething() throws Exception{
logger.info("printSomething{} is called");
throw new SQLException();
}
This #Retryable annotation will retry/call retrySomething() 5 times (including the 1st failure).
Current thread will wait for 3000 ms or 3 seconds between next retry.
I have one answer already, but it was three years ago and I have to add that now I absolutley love guava-retrying project. Let me just show you the code.
Callable<Boolean> callable = new Callable<Boolean>() {
public Boolean call() throws Exception {
return true; // do something useful here
}
};
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
.retryIfResult(Predicates.<Boolean>isNull())
.retryIfExceptionOfType(IOException.class)
.retryIfRuntimeException()
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
.build();
try {
retryer.call(callable);
} catch (RetryException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
One option to factor this out of your codebase is to use the command pattern between the components of your application.
Once you turn a call to a business method into an object, you can hand around the call easily and have an abstract RetryHandler that takes a command and retries it. This should be independent from the actual call and reusable.
I have implemented a pretty flexible retry utility here
You can retry any Callable with:
public static <T> T executeWithRetry(final Callable<T> what, final int nrImmediateRetries,
final int nrTotalRetries, final int retryWaitMillis, final int timeoutMillis,
final Predicate<? super T> retryOnReturnVal, final Predicate<Exception> retryOnException)
with immediate + delayed retries, with a max timeout, and retry either on decisions based on result or exception.
There are several other versions of this function with more or less flexibility.
I have written also a aspect that can be applied with annotations Retry Retry Aspect
You can use Quartz. Look at this Stack Overflow answer.

Spring 3: task namespace: How to find out time of next execution?

I have a bean that has a method executed on a schedule using <task:scheduled> in the context configuration.
Is there a way for me to find the time of the next scheduled run during execution of that method?
The same method is also executed manually, and the mechanism for receiving scheduler information may not break executions from outside the scheduler...
The <task:scheduled> configuration style is a convenient shortcut on to underlying Spring factory beans that generate schedulers and schedules. As a convenience, it's useful, but is much less flexible than using the underlying scheduler factories directly.
Having said that, the schedulers themselves would need to expose the "next fire time" information via their API, and that's implementation-dependent. For example, I don't see a way to get this information from the standard ScheduledExecutorService implementations.
Quartz, however, does expose this, via the getNextFireTime() method on the Trigger class.
If you're willing to abandon <task:scheduled> and use the Quartz-Spring integration directly, then you can get access to the Trigger (or TriggerBean) and get what you want that way.
For those not using quartz but spring, I have achieved to get next execution time by extending CronTrigger and remembering nextExecutionTime:
import org.springframework.scheduling.support.CronTrigger;
public class MyCronTrigger extends CronTrigger {
public MyCronTrigger(String expression) {
super(expression);
}
#Override
public Date nextExecutionTime(TriggerContext triggerContext) {
Date date = super.nextExecutionTime(triggerContext);
nextExecutionTime = new Date(date.getTime()); //remember
return date;
}
}

Categories