title: How to delete session data at a regular time interval, every hour?
body: <p>I'm generating random tokens for the reason as mentioned in this <a href="https://stackoverflow.com/q/16114525/1391249">question</a> which are placed in a <code>java.util.List</code> and this <code>List</code> is kept in a session scope. </p>
  
  <p>After going through some Google search, I have decided to remove all elements (tokens) every hour contained by this <code>List</code> in session.</p>
  
  <p>I could think of using the <a href="http://quartz-scheduler.org/overview/quick-start" rel="nofollow noreferrer">Quartz</a> API but doing so, doesn't seem possible for manipulating a user's session. What I have tried with the Quartz API (1.8.6, 2.x is incompatible with Spring 3.2 which I'm using) in Spring can be seen below.</p>
  
  <pre><code>package quartz;
  
  import org.quartz.JobExecutionContext;
  import org.quartz.JobExecutionException;
  import org.springframework.scheduling.quartz.QuartzJobBean;
  
  public final class RemoveTokens extends QuartzJobBean
  {    
      @Override
      protected void executeInternal(JobExecutionContext context) throws JobExecutionException
      {
          System.out.println("QuartzJobBean executed.");
      }
  }
  </code></pre>
  
  <p>And it was configured in the <code>application-context.xml</code> file as follows.</p>
  
  <pre><code>&lt;bean name="removeTokens" class="org.springframework.scheduling.quartz.JobDetailBean"&gt;
      &lt;property name="jobClass" value="quartz.RemoveTokens" /&gt;
      &lt;property name="jobDataAsMap"&gt;
          &lt;map&gt;
              &lt;entry key="timeout" value="5" /&gt;
          &lt;/map&gt;
      &lt;/property&gt;
  &lt;/bean&gt;
  
  &lt;bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean"&gt;
        &lt;property name="jobDetail" ref="removeTokens"/&gt;
        &lt;property name="startDelay" value="10000"/&gt;
        &lt;property name="repeatInterval" value="3600000"/&gt;
  &lt;/bean&gt;
  
  &lt;bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"&gt;
    &lt;property name="triggers"&gt;
        &lt;list&gt;
            &lt;ref bean="simpleTrigger" /&gt;
        &lt;/list&gt;
    &lt;/property&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p>The overridden method in the <code>RemoveTokens</code> class is executed every hour with the initial interval of 10 seconds as configured in XML but it is not possible to execute some method of some class to remove the tokens available in the <code>List</code> which is stored in a user's session. Is it possible?</p>
  
  <p>What is the fair way to remove this <code>List</code> stored in a session scope with a defined time interval (every hour)? It would be far better, if it were to be made possible by using this Quartz API.</p>
  
  <hr>
  
  <p><strong>EDIT:</strong></p>
  
  <p>According to the answer below, I have tried the following but unfortunately, it didn't make a difference.</p>
  
  <p>In the <code>application-context.xml</code> file,</p>
  
  <pre><code>&lt;task:annotation-driven executor="taskExecutor" scheduler="taskScheduler"/&gt;
  &lt;task:executor id="taskExecutor" pool-size="5"/&gt;
  &lt;task:scheduler id="taskScheduler" pool-size="10"/&gt;
  </code></pre>
  
  <p>This requires the following additional namespaces,</p>
  
  <pre><code>xmlns:task="http://www.springframework.org/schema/task"
  xsi:schemaLocation="http://www.springframework.org/schema/task
                      http://www.springframework.org/schema/task/spring-task-3.2.xsd"
  </code></pre>
  
  <p>The following bean was registered as a session scoped bean.</p>
  
  <pre><code>package token;
  
  import java.util.ArrayList;
  import java.util.List;
  import java.util.Random;
  import org.apache.commons.lang.StringUtils;
  import org.springframework.context.annotation.Scope;
  import org.springframework.stereotype.Service;
  
  @Service
  //@Scope("session")
  public final class SessionToken implements SessionTokenService
  {
      private List&lt;String&gt; tokens;
  
      private static String nextToken()
      {
          long seed = System.currentTimeMillis(); 
          Random r = new Random();
          r.setSeed(seed);
          return Long.toString(seed) + Long.toString(Math.abs(r.nextLong()));
      }
  
      @Override
      public boolean isTokenValid(String token)
      {        
          return tokens==null||tokens.isEmpty()?false:tokens.contains(token);
      }
  
      @Override
      public String getLatestToken()
      {
          if(tokens==null)
          {
              tokens=new ArrayList&lt;String&gt;(0);
              tokens.add(nextToken());            
          }
          else
          {
              tokens.add(nextToken());
          }
  
          return tokens==null||tokens.isEmpty()?"":tokens.get(tokens.size()-1);
      }
  
      @Override
      public boolean unsetToken(String token)
      {                
          return !StringUtils.isNotBlank(token)||tokens==null||tokens.isEmpty()?false:tokens.remove(token);
      }
  
      @Override
      public void unsetAllTokens()
      {
          if(tokens!=null&amp;&amp;!tokens.isEmpty())
          {
              tokens.clear();
          }
      }
  }
  </code></pre>
  
  <p>And interface which it implements,</p>
  
  <pre><code>package token;
  
  import java.io.Serializable;
  
  public interface SessionTokenService extends Serializable
  {
      public boolean isTokenValid(String token);
      public String getLatestToken();
      public boolean unsetToken(String token);
      public void unsetAllTokens();
  }
  </code></pre>
  
  <p>And this bean was configured in the <code>application-context.xml</code> file as follows.</p>
  
  <pre><code>&lt;bean id="sessionTokenCleanerService" class="token.SessionToken" scope="session"&gt;
      &lt;aop:scoped-proxy proxy-target-class="false"/&gt;
  &lt;/bean&gt;
  </code></pre>
  
  <p>Now, I'm injecting this service in the following class.</p>
  
  <pre><code>package token;
  
  import org.springframework.beans.factory.annotation.Autowired;
  import org.springframework.scheduling.annotation.Scheduled;
  import org.springframework.stereotype.Service;
  
  @Service
  public final class PreventDuplicateSubmission
  {    
      @Autowired
      private final SessionTokenService sessionTokenService=null;
  
      @Scheduled(fixedDelay=3600000)
      public void clearTokens()
      {
          System.out.println("Scheduled method called.");
          sessionTokenService.unsetAllTokens();            
      }
  }
  </code></pre>
  
  <p>And in the <code>application-context.xml</code> file,</p>
  
  <pre><code>&lt;bean id="preventDuplicateSubmissionService" class="token.PreventDuplicateSubmission"/&gt;
  </code></pre>
  
  <p>Both of the above beans are annotated with the <code>@Service</code> and they should be part of <code>context:component-scan</code> in the <code>dispatacher-servelt.xml</code> file (or whatever its name).</p>
  
  <p>The method annotated with the <code>@Scheduled</code> annotation in the preceding code snippet is invoked regularly at the given rate but it causes the following obvious exception to be thrown.</p>
  
  <pre><code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.sessionTokenCleanerService': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:343)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
      at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:33)
      at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:184)
      at $Proxy79.unsetAllTokens(Unknown Source)
      at token.PreventDuplicateSubmission.clearTokens(PreventDuplicateSubmission.java:102)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:601)
      at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:64)
      at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:53)
      at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
      at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:351)
      at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:178)
      at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:178)
      at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
      at java.lang.Thread.run(Thread.java:722)
  Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
      at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:131)
      at org.springframework.web.context.request.SessionScope.get(SessionScope.java:90)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:329)
      ... 19 more
  </code></pre>
  
  <p>To clear data stored in a user's session, the method that does this task should be invoked regularly at a defined time interval <strong>from every user's session</strong> which is not the case with this attempt. What is the way? The question may simply be : how to trigger a regular time interval from every user's session?    Does Spring or Servlet API support something to accomplish this?</p>