samwise
samwise

Reputation: 299

What can I use to implement a background process for each session in java servlets running on tomcat?

I wish to run a function for every user with a session at regular intervals that will check if a user is active. If not active, the function will remove the user from the list of users in the servlet context and clear the user session.

What can I use that will run the function at regular timed intervals for each user?

From what I understand, servletcontextlistener runs only once for the life of the servlet and not for each user so it's not usable. Also, that using threads is advised against in a servlet.

Edit: Users (using ajax) call a action which contains function that updates a variable I've stored for each user that indicates the last time they contacted the server.

Upvotes: 3

Views: 381

Answers (2)

Vladimir
Vladimir

Reputation: 2553

Two ways I can think off the top of my head:

  1. Use request.getSession().setMaxInactiveInterval(someValue)

  2. Since you're using ajax, instead of sending the "user activity" value you might as well send the actual "kill session" request. This would mean less http calls, since the logic of whether the user is active or not is on the client side, while the actual "session kill" logic is on the backend. So here is the scenario:

    Javascript code runs every minute to check whether the user is active or not (not sure what you're actually looking at, but that's a different story). If after, say, 5 minutes the user hasn't done anything on the client side, then an ajax call is sent to the backend to kill the session.

Upvotes: 1

Knut Forkalsrud
Knut Forkalsrud

Reputation: 1174

You are probably looking for javax.servlet.http.HttpSessionListener. Create one, register it in web.xml and have the sessionDestroyed do your work.

Upvotes: 2

Related Questions